I am new to creating jQuery plugins. I saw and used a lot of tooltip plugins, and today I decided to create my own.
Can I get a link back to the code? What work and what not. Optimization. Caching
What can I do to make it faster and better?
It would be very useful for my training and, hopefully, for others too.
Here is my plugin:
;(function($) { $.fn.jTooltip = function(options) { opts = $.extend({}, $.fn.jTooltip.defaults, options); return this.each(function() { var $this = $(this); var content; var showTimeout; $tip = $('#jTooltip'); if($tip.size() == 0){ $('body').append('<div id="jTooltip" style="display:none;position:absolute;"><div></div></div>'); $tipContent = $('#jTooltip div'); } $this.mouseover(function(event) { content = $this.attr('title'); $this.attr('title', ''); $tipContent.html(content); $body.bind('mousemove', function(event){ $tip.css({ top: $(document).scrollTop() + (event.pageY + opts.yOffset), left: $(document).scrollLeft() + (event.pageX + opts.xOffset) }); }); showTimeout = setTimeout('$tip.fadeIn(' + opts.fadeTime + ')', opts.delay); }); $this.mouseout(function(event) { clearTimeout(showTimeout); $this.attr('title', content); $('body').unbind('mousemove'); $tip.hide(); }); }); }; $.fn.jTooltip.defaults = { delay: 0, fadeTime: 300, yOffset: 10, xOffset: 10 }; })(jQuery);
Updated Code
;(function($) { $.fn.jTooltip = function(options) { opts = $.extend({}, $.fn.jTooltip.defaults, options); return this.each(function() { var $this = $(this); var showTimeout; $this.data('title',$this.attr('title')); $this.removeAttr('title'); $document = $(document); $body = $('body'); $tip = $('#jTooltip'); $tipContent = $('#jTooltip div'); if($tip.length == 0){ $body.append('<div id="jTooltip" style="display:none;position:absolute;"><div></div></div>'); } $this.hover(function(event){ $tipContent.html($this.data('title')); $body.bind('mousemove', function(event){ $tip.css({ top: $document.scrollTop() + (event.pageY + opts.yOffset), left: $document.scrollLeft() + (event.pageX + opts.xOffset) }); }); showTimeout = setTimeout(function(){ $tip.fadeIn(opts.fadeTime); }, opts.delay); }, function(){ clearTimeout(showTimeout); $body.unbind('mousemove'); $tip.hide(); }); }); }; $.fn.jTooltip.defaults = { delay: 0, fadeTime: 300, yOffset: 10, xOffset: 10 }; })(jQuery);
Let me know if you have more feedback;)
source share