Skip to content

Instantly share code, notes, and snippets.

@jashkenas
Created July 18, 2012 20:55
Show Gist options
  • Save jashkenas/3138833 to your computer and use it in GitHub Desktop.
Save jashkenas/3138833 to your computer and use it in GitHub Desktop.
.tooltip {
position: absolute;
padding: 8px 10px;
border: 1px solid #999;
z-index: 100;
width: 100px;
background: #fff;
font: 11px/14px Arial;
box-shadow: 0 2px 4px rgba(0,0,0,0.3);
}
.tooltip-title {
margin: 3px 0;
color: #000;
font-weight: bold;
}
.tooltip-text {
color: #555;
}
<div class="tooltip" style="display:none;">
<div class="tooltip-title"></div>
<div class="tooltip-text"></div>
</div>
var enableTooltips = function() {
var tooltip = $('.tooltip');
var width = tooltip.width();
var margin = 30;
var fudge = 10;
var visible = false;
var openTooltip = function(e) {
var el = $(e.currentTarget);
tooltip.find('.tooltip-title').text(el.attr('data-title'));
tooltip.find('.tooltip-text').text(el.attr('data-text'));
tooltip.show();
visible = true;
};
var moveTooltip = function(e) {
if (!visible) return;
var winWidth = $(window).width();
var inBounds = (e.pageX + width + margin + fudge) < winWidth;
var x = inBounds ? e.pageX + fudge : e.pageX - (width + margin);
tooltip.css({left: x + 'px', top: e.pageY + 10 + 'px'});
};
var closeTooltip = function() {
tooltip.hide();
visible = false;
};
$('.tooltip-container').on('mouseenter', '.has-tooltip', openTooltip);
$('.tooltip-container').on('mouseleave', '.has-tooltip', closeTooltip);
$('.tooltip-container').on('mousemove', moveTooltip);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment