Created
May 26, 2015 01:12
-
-
Save grom358/57f532e2df719807fa1a to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
;(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