In this post we will show you how to display a tooltip over the slider thumb when we drag it. We’ll skip the
initialization of the jqxSlider and will move to the tooltip implementation.
1. Add the CSS style settings for the tooltip.
<style type="text/css">
.tooltip
{
position: absolute;
width: 20px;
height: 15px;
background: black;
color: white;
font-size: 13px;
z-index: 20;
padding: 3px;
text-align: center;
}
</style>
2. The ‘createTooltip’ function below will create the tooltip and add it to the document’s body.
function createTooltip() {
var tooltip = $('<div />');
$(document.body).append(tooltip);
tooltip.css('visibility', 'hidden');
tooltip.fadeTo(0, 0.6);
tooltip.addClass('jqx-rc-all');
tooltip.addClass('tooltip');
return tooltip;
}
3. The ‘refreshTooltip’ function updates the tooltip’s position and text.
function refreshTooltip(value) {
var thumb = $($('#slider').find('.jqx-slider-slider')[1]),
thumbX = thumb.offset().left,
thumbY = thumb.offset().top;
tooltip.css('left', thumbX - (tooltip.outerWidth(true) - thumb.outerWidth(true)) / 2);
tooltip.css('top', thumbY - tooltip.outerHeight(true) - 3);
tooltip.text(value);
}
Let’s see how it works:
At first, we find the thumb’s position. Then we save the ‘left’ and ‘top’ position in the thumbX and thumbY fields. After that we position the tooltip. Finally, we set the tooltip’s text to the slider value.
4. Now, it is time to implement the logic when the tooltip should be visible or hidden.
We will trigger the ‘mousedown’, ‘mousemove’ and ‘mouseup’ events.
In the ‘mousedown’ handler, we will show the tooltip and set its text and position.
The ‘mousemove’ handler will update the position and text. In the ‘mouseup’ handler, we will hide the tooltip.
var thumb = $($('#slider').find('.jqx-slider-slider')[1]),
tooltip = createTooltip(),
tooltipActive = false;
thumb.bind('mousedown', function (event) {
tooltip.css('visibility', 'visible');
refreshTooltip($('#slider').jqxSlider('value'));
tooltipActive = true;
});
$(document).bind('mousemove', function (event) {
if (tooltipActive) {
refreshTooltip($('#slider').jqxSlider('value'));
}
});
$(document).bind('mouseup', function () {
tooltip.css('visibility', 'hidden');
tooltipActive = false;
});
Here’s how it looks: