Monday, October 4, 2010

Interface Components known as Tooltips

These are the message boxes that appear over a control when an end user hovers over one. You have probably already seen tooltips before in many places on the world wide web. For example when you provide a title attribute for a link or an alt attribute for an image you will usually get that hover effect when viewed in most browsers. These tooltips usually give some useful information about what the link is going to do or what the image is doing in the DOM. It's relatively easy in jQuery to customize the tooltips. Let's say that we have a simple link:

<a href="someOtherLink.html" title="I will take you to some other link">Simple Link</a>

This is just a basic link; but with jQuery we can really make this pop.

// this handles when we hover over the element
$('.someText').hover(function(expression)
{ var theText = $(this).attr('title');
   $(this).data('theToolTipText', theText).removeAttr('title');
  
   $('<p class="theToolTip"></p>').text(theText).appendTo('body').fadeIn('fast');

 },  // now address when we hover off the element with a callback
 function()
 { $(this).attr('title', $(this).data('theToolTipText'));
    $('.theToolTip').remove();
  });

We have now created a small pop up message letting us know what the title of this link or paragraph is without relying on the alt attribute or similar. We handle the hover out effect by calling the remove method on the element and just like that the message is gone!

No comments:

Post a Comment