Skip to content

Instantly share code, notes, and snippets.

@grom358
Created May 26, 2015 01:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save grom358/57f532e2df719807fa1a to your computer and use it in GitHub Desktop.
Save grom358/57f532e2df719807fa1a to your computer and use it in GitHub Desktop.
;(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