Created
February 2, 2012 09:33
-
-
Save c4urself/1722562 to your computer and use it in GitHub Desktop.
jquery tooltip
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
| define([ 'jquery' ], function($) { | |
| var Tooltip = function(element, options) { | |
| this.$element = $(element); | |
| var tooltip = this, | |
| title = this.$element.attr('title'); | |
| this.options = $.extend({}, $.fn.tooltip.defaults, options); | |
| this.text = this.$element.removeAttr('title') && title || this.options.text; | |
| this.$element.bind('mouseover', function() {tooltip.show()}); | |
| this.$element.bind('mouseout', function() {tooltip.hide()}); | |
| }; | |
| Tooltip.prototype = { | |
| template: $('<div class="tt-wrapper"><div class="tt-arrow tt-arrow-left"></div><div class="tt-content"></div></div>'), | |
| setDimensions: function() { | |
| var el = this.$element; | |
| var callerOffsetTop = parseInt(el.offset().top, 10), | |
| callerOffsetLeft = parseInt(el.offset().left, 10), | |
| callerHeight = el.outerHeight(), | |
| callerWidth = el.outerWidth(); | |
| var tooltipHeight = $(".tt-wrapper").outerHeight(), | |
| tooltipWidth = $(".tt-wrapper").outerWidth(), | |
| tooltipLeft = callerWidth + callerOffsetLeft, | |
| tooltipTop = callerOffsetTop + (parseInt(callerHeight - tooltipHeight, 10) / 2); | |
| if ((tooltipLeft + tooltipWidth) > $(window).width()) { | |
| $(".tt-arrow").removeClass("tt-arrow-left"); | |
| $(".tt-arrow").addClass("tt-arrow-right"); | |
| tooltipLeft = (callerOffsetLeft - tooltipWidth); | |
| } else if ($(".tt-arrow").hasClass("tt-arrow-right")) { | |
| $(".tt-arrow").removeClass("tt-arrow-right"); | |
| $(".tt-arrow").addClass("tt-arrow-left"); | |
| } | |
| $(".tt-wrapper").css("left", tooltipLeft + "px"); | |
| $(".tt-wrapper").css("top", tooltipTop + "px"); | |
| }, | |
| show: function() { | |
| this.template.appendTo('body'); | |
| var $container = $(".tt-content"); | |
| $container.empty().html(this.text); | |
| $container.width(this.options.width); | |
| this.setDimensions(); | |
| }, | |
| hide: function() { | |
| var tooltip = $('.tt-wrapper'); | |
| tooltip.remove(); | |
| } | |
| }; | |
| $.fn.tooltip = function(option) { | |
| return this.each(function () { | |
| var $this = $(this), | |
| data = $this.data('tooltip'), | |
| options = typeof option == 'object' && option; | |
| if (!data) { | |
| $this.data('tooltip', (data = new Tooltip(this, options))); | |
| } else if (typeof option == 'string') { | |
| data[option](); | |
| } | |
| }); | |
| }; | |
| $.fn.tooltip.defaults = { | |
| width: 500, | |
| text: 'Example text' | |
| }; | |
| }); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment