MainelyDesign.com Blog

Controlling jQuery's Tooltip

Posted on 07/25/2014 at 09:40 am by Kevin Wentworth
Viewed 8,955 times | 0 comments

After watching jQuery's tooltip() slow down a page's loading time by a solid two seconds, it became clear that there had to be a better way to create and control tooltips.

The Slow Way

The initial use of tooltip() was used to create all of the tooltips on page generation, as such...

  1. $(".tooltip").tooltip({
  2.     position: {
  3.         my: "center bottom-20",
  4.         at: "center top",
  5.         using: function( position, feedback ) {
  6.             $( this ).css( position );
  7.             $( "<div>" )
  8.             .addClass( "arrow" )
  9.             .addClass( feedback.vertical )
  10.             .addClass( feedback.horizontal )
  11.             .appendTo( this );
  12.         }
  13.     }
  14. });

Using this, if a page has, say, 200 tooltips being generated all at once, guess what? Slow loading all around! Now, what if we were to create the tooltip by hovering the tooltip element, and then destroying it when you stop hovering it?

The Fast Way

Using jQuery's hoverIntent listener, we can control how tooltips are generated and listed, as such...

  1. $(".tooltip").hoverIntent({
  2.     over: function(){
  3.         // On mouseenter
  4.         $(this).tooltip({
  5.             position: {
  6.                 my: "center bottom-20",
  7.                 at: "center top",
  8.                 using: function( position, feedback ) {
  9.                     $( this ).css( position );
  10.                     $( "<div>" )
  11.                     .addClass( "arrow" )
  12.                     .addClass( feedback.vertical )
  13.                     .addClass( feedback.horizontal )
  14.                     .appendTo( this );
  15.                 }
  16.             }
  17.         });
  18.         // Generate tooltip, then open it.
  19.         $(this).tooltip("open");
  20.     },
  21.     out: function(){
  22.         // On mouseleave
  23.         $(this).tooltip("close", function(){
  24.             // Wait to close, then destroy instance
  25.             $(this).tooltip("destroy");
  26.         });
  27.     },
  28. });

Now, instead of creating and leaving every tooltip on page generation, the tooltips are generated on hover of the tooltip element, then deleted when you leave the element.

Hooray! Faster loading times!

Good Luck, Fellow Programmers.

Bookmark and Share

Tags for Controlling jQuery's Tooltip

Jquery | Tutorial | Web Programming

Comments for this Posting

No comments. Be the first to post a reply.

Sorry, comments are closed for this posting.

Please Email Kevin if you have any questions. Thanks!

Meet Site Avenger - Hosted Content Management System

Powered By: Site Avenger | Site Production: Saco Design