Javascript: Using Bootstrap tooltips with jQuery UI’s slider

Earlier today, I was adding a “slider” UI element to a project that was using Twitter Bootstrap as well as jQuery UI. Although they weren’t designed to work together, the two projects generally stay out of each other’s way since their CSS classes are namespaced pretty well.

Since jQuery UI was already loaded I naturally decided to just use the jQuery UI slider control to power the slider. One of the limitations with the jQuery UI slider is that it has no native way to show the current slider value over the slider handle, as a developer you have to display that number somewhere. Fortunately, the control has the event hooks neccesary to make this happen – specifically the slide event which is triggered everytime the slider is moved.

With Bootstrap also loaded, I decided to try and use the tooltip plugin to dynamically display the current value of the slider above the handle. Getting the initual tooltip setup was pretty straightforward. Check it out here.

But the issue is that even with the “slide” event, the Bootstrap tooltip plugin has no exposed method to force a reposition. The only way to get a tooltip to reposition itself is to hide it and then show it again. Obviously, that’s less than ideal since you get a noticible “jump” as the tooltip is hid and then shown again.

With this issue in mind, I decided to take a look at how the Tooltip plugin actually does the positioning. It turns out it’s really simple, the relevant code is on GitHub. Ok, so its easy to reposition them but how do you get the “right” tooltip div incase you have multiple sliders? Looking through the code, the Tooltip plugin actually uses the jQuery.data() function to store config options and additionally stores a reference to the correct div there. Getting a handle to the correct div is as easy as $(“#slider .ui-slider-handle:first”).data(“tooltip”).$tip

Looking at the actual plugin code, it’s simple enough to just copy that out and use it to reposition the tooltips. Check it out in action at http://jsfiddle.net/cqVPM/7/

Anyway, let me know if you run into any issues in the comments.