Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
;(function($) {
function Tooltip(elem, conf) {
// Create tooltip
var tooltip = $('<div></div>')
.addClass(conf.className)
.html(elem.attr('title'))
.insertAfter(elem);
tooltip.hide();
// Remove the browser tooltip
elem.removeAttr('title');
function setPosition(posX, posY) {
tooltip.css({ left: posX, top: posY });
}
function updatePosition(event) {
var tooltipWidth = tooltip.outerWidth();
var tooltipHeight = tooltip.outerHeight();
var $window = $(window);
var windowWidth = $window.width() + $window.scrollLeft();
var windowHeight = $window.height() + $window.scrollTop();
var posX = event.pageX + conf.offset[0];
var posY = event.pageY + conf.offset[1];
if (posX + tooltipWidth > windowWidth) {
// Move left
posX = windowWidth - tooltipWidth;
}
if (posY + tooltipHeight > windowHeight) {
// Move tooltip to above cursor
posY = event.pageY - conf.offset[1] - tooltipHeight;
}
setPosition(posX, posY);
}
elem.hover(
// Show
function(event) {
updatePosition(event);
conf.show(tooltip);
},
// Hide
function() {
conf.hide(tooltip);
}
);
}
$.fn.tooltip = function(conf) {
var defaultConf = {
offset: [10, 10],
className: 'tooltip',
show: function(tooltip) {
tooltip.fadeIn(150);
},
hide: function(tooltip) {
tooltip.fadeOut(150);
}
};
$.extend(defaultConf, conf);
this.each(function() {
var el = new Tooltip($(this), defaultConf);
$(this).data("tooltip", el);
});
}
})(jQuery);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.