Jquery Easy Tooltip Generator


/ Published in: jQuery
Save to your folder(s)

Also includes the fix for when the user resizes the window.


Copy this code and paste it in your HTML
  1. $.fn.betterTooltip = function(options){
  2.  
  3. /* Setup the options for the tooltip that can be
  4. accessed from outside the plugin */
  5. var defaults = {
  6. speed: 200,
  7. delay: 300
  8. };
  9.  
  10. var options = $.extend(defaults, options);
  11.  
  12. /* Create a function that builds the tooltip
  13. markup. Then, prepend the tooltip to the body */
  14. getTip = function() {
  15. var tTip =
  16. "<div class='tip'>" +
  17. "<div class='tipMid'>" +
  18. "</div>" +
  19. "<div class='tipBtm'></div>" +
  20. "</div>";
  21. return tTip;
  22. }
  23. $("body").prepend(getTip());
  24.  
  25. /* Give each item with the class associated with
  26. the plugin the ability to call the tooltip */
  27. $(this).each(function(){
  28.  
  29. var $this = $(this);
  30. var tip = $('.tip');
  31. var tipInner = $('.tip .tipMid');
  32.  
  33. var tTitle = (this.title);
  34. this.title = "";
  35.  
  36.  
  37. /* Mouse over and out functions*/
  38. $this.hover(
  39. function() {
  40. /* so we can calculate correct position even on resize / change of tab */
  41. var tWidth = $this.width();
  42. var tHeight = $this.height();
  43. var offset = $(this).offset();
  44. var tLeft = offset.left + (tWidth/2);
  45. var tTop = offset.top;
  46. tipInner.html(tTitle);
  47. setTip(tTop, tLeft);
  48. setTimer();
  49. },
  50. function() {
  51. stopTimer();
  52. tip.hide();
  53. }
  54. );
  55.  
  56. /* Delay the fade-in animation of the tooltip */
  57. setTimer = function() {
  58. $this.showTipTimer = setInterval("showTip()", defaults.delay);
  59. }
  60.  
  61. stopTimer = function() {
  62. clearInterval($this.showTipTimer);
  63. }
  64.  
  65. /* Position the tooltip relative to the class
  66. associated with the tooltip */
  67. setTip = function(top, left){
  68. var topOffset = tip.height();
  69. var xTip = (left-20)+"px";
  70. var yTip = (top-topOffset-35)+"px";
  71. tip.css({'top' : yTip, 'left' : xTip});
  72. }
  73.  
  74. /* This function stops the timer and creates the
  75. fade-in animation */
  76. showTip = function(){
  77. stopTimer();
  78. tip.animate({"top": "+=20px", "opacity": "toggle"}, defaults.speed);
  79. }
  80. });
  81. };

URL: http://net.tutsplus.com/tutorials/javascript-ajax/build-a-better-tooltip-with-jquery-awesomeness/

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.