jQuery User Interface Plugins: Tooltip Plugins

Exclusive offer: get 50% off this eBook here
jQuery Plugin Development Beginner's Guide

jQuery Plugin Development Beginner's Guide — Save 50%

Build powerful, interactive plugins to implement jQuery in the best way possible

$26.99    $13.50
by Giulio Bai | October 2010 | Beginner's Guides Open Source Web Development

We might want to start off by saying tooltips are very popular in today's web design. This is probably due to the value that the tooltips add to the overall look of a website and the sensible addition to a nice user experience that they will certainly contribute. Also, as we have seen for many other plugins, which are not that difficult to create—provided we know exactly what to do and how to do it—there shouldn't be much of an issue with developing the tooltip plugin. It may actually take some time to understand how to position elements based on the mouse cursor position itself and how to move deftly with an increasing number of functions doing different things. However, we're now on the path to becoming experts, and fearless too!

The topics we're going to discuss in this article by Giulio Bai, author of jQuery Plugin Development Beginner's Guide, include:

  • Tooltip plugins in general
  • Positioning the tooltip
  • Merging pieces together
  • Custom jQuery selectors

 

jQuery Plugin Development Beginner's Guide

jQuery Plugin Development Beginner's Guide

Build powerful, interactive plugins to implement jQuery in the best way possible

  • Utilize jQuery's plugin framework to create a wide range of useful jQuery plugins from scratch
  • Understand development patterns and best practices and move up the ladder to master plugin development
  • Discover the ins and outs of some of the most popular jQuery plugins in action
  • A Beginner's Guide packed with examples and step-by-step instructions to quickly get your hands dirty in developing high quality jQuery plugins
        Read more about this book      

(For more resources on jQuery, see here.)

Before we get started, there is another little thing worth mentioning: provide many different opportunities to introduce new concepts and ideas, even while keeping the complexity of the whole plugin at a minimum.

We can now go on to create our plugin, starting with basic functionalities, and subsequently adjusting its goals. We will add new, improved functionalities that, however, do not make the whole code look too difficult to understand—even after some time or for someone who's just starting out with jQuery.

Tooltip plugins in general

A lot has been said about tooltip plugins, but it's worth repeating the most important points with particular regard to the way tooltips are supposed to work, and how we want our tooltip to behave.

First of all, we might want to get an idea of what tooltips look like and a sample of what we will accomplish by the end of this article. Here is an example:

Also, with some more work and proper application of effects, images, and other relatively advanced techniques, we can also obtain something more complex and nicer looking, thus giving the user the chance to specify the style and behavior for the tooltip, as follows:

The idea is actually very simple. The elements we have selected will trigger an event every time we hover the mouse pointer over them.

The tooltip will then pop out, right at the mouse cursor position, retrieving the text portion from the title attribute of the said element.

Finally, whenever we move the mouse over the same element, the plugin will move and follow the mouse cursor until it goes off the boundaries of the element.

Positioning the tooltip

The first problem we have to face is, of course, how to make the tooltip appear in the right position.

It would be no trouble at all if we just had to make some text, image, or anything else show up. We've done it many times and it's no problem at all—just make their positioning absolute and set the right top and side distances.

However, we need to take into account the fact that we don't know exactly where the mouse cursor might be and, as such, we need to calculate distances based upon the mouse cursor position itself.

So, how can we do it? It's simple enough; we can use some of the JavaScript event properties to obtain the position. Unfortunately, Internet Explorer always tries to put a spoke in our wheel.

In fact, the magnificent browser does not (according to this table, which is quite accurate: http://www.quirksmode.org/dom/w3c_cssom.html#mousepos) support pageX and pageY, which would normally return the mouse coordinates relative to the document.

So we need to think about a workaround for Internet Explorer, as jQuery (from version 1.0.4 onwards) does not normalize some of the event properties according to W3C standards (http://api.jquery.com/category/events/event-object/).

The following diagram (also provided in the " target="_blank">code bundle) should clarify what the visible viewport is (that is, the browser window—the red box):

Whenever we scroll down, different parts of the document (blue) are shown through the browser window and hidden due to space constraints. The scroll height (green) is the part of the document currently not displayed.

Custom jQuery selectors

Suppose we have a page with some text written in, which also contains a few links to both internal pages (that is, pages on the same server) and external websites.

We are presented with different choices in terms of which elements to apply the tooltip to (referring to links as an example, but they apply to any kind of element as well), as follows:

  • All the links
  • All the links with a specific class (for example, tooltip)
  • All the links with the title attribute not empty
  • All the links pointing to internal pages
  • All the links pointing to external websites
  • Combinations of the above

We can easily combine the first three conditions with the others (and with themselves) using CSS selectors appropriately. For example:

  • $("a"), all the links
  • $("a.tooltip"), links having a tooltip class
  • $("a[title]"), links with a title attribute (still have to check if empty)
  • $("a.tooltip[title]"), links with a tooltip class and a title attribute

As for internal and external pages, we have to work with jQuery selectors instead.

Time for action – creating custom jQuery selectors

Although jQuery makes it easy to select elements using standard CSS selectors, as well as some other selectors, jQuery's own selectors are the ones that help the developer to write and read code. Examples of custom selectors are :odd, :animated, and so on.

jQuery also lets you create your own selectors!

  1. The syntax is as follows:

    // definition
    $.expr[':'].customselector = function(object, index,
    properties, list) {
    // code goes here
    };
    // call
    $("a:customselector")

  2. The parameters are all optional except for the first one (of course!), which is required to perform some basic stuff on the selected object:
    • object: Reference to current HTML DOM element (not jQuery, beware!)
    • index: Zero-based loop index within array
    • properties: Array of metadata about the selector (the 4th argument contains the string passed to the jQuery selector)
    • list: Array of DOM elements to loop through
  3. The return value can be either:
    • true: Include current element
    • false: Exclude current element
  4. Our selector (for external links detection) will then look, very simply, like the following code:

    $.expr[':'].external = function(object) {
    if(object.hostname) // is defined
    return(object.hostname != location.hostname);
    else return false;
    };

  5. Also note that, to access the jQuery object, we have to use the following (since object refers to the DOM element only!):

    $.expr[':'].sample = function(object) {
    alert('$(obj).attr(): ' + $(object).attr("href") +
    'obj.href: ' + object.href);
    };

Merging pieces together

We have slowly created different parts of the plugin, which we need to merge in order to create a working piece of code that actually makes tooltips visible.

So far we have understood how positioning works and how we can easily place an element in a determined position.

Also, we have found out we can create our own jQuery selectors, and have developed a simple yet useful custom selector with which we are able to select links pointing to either internal or external pages. It needs to be placed at the top of the code, inside the closure, as we will make use of the dollar symbol ($) and it may conflict with other software.

jQuery Plugin Development Beginner's Guide Build powerful, interactive plugins to implement jQuery in the best way possible
Published: October 2010
eBook Price: $26.99
Book Price: $44.99
See more
Select your format and quantity:
        Read more about this book      

(For more resources on jQuery, see here.)

Time for action – creating a tooltip plugin

We still need to think of a way to actually make the tooltip show up and disappear, which is no big deal after all. Let's see how.

  1. You should have created the directory containing the right files by now; but anyway, call the plugin file jquery.tooltip.js and let's move on.
  2. After copying and pasting the code from the various files we used before, we should end up with something like this:

    (function($) {
    $.expr[':'].external = function(object) {
    return(object.hostname != location.hostname);
    };

    $.fn.tooltip = function() {
    return this.each(function() {
    $(this).hover(function(event) {
    // mouse hover
    }, function() {
    // mouse leaves
    }).mousemove(function(event) {
    // mouse moves
    });
    });
    };
    })(jQuery)

  3. We have to take care of a few things now:
    • Check if the element is actually a link (who knows!)
    • Check if the title attribute is not empty
    • Make sure that the default tooltip is not displayed
    • Apply CSS styling to the tooltip
  4. We can then add the following code at the very start of the each loop. The event binding will, therefore, be conditioned to the fact that the selected element is an element with a title attribute.

    Also, we will remove the title content so that the default tooltip will not show up (note we first save the title content so that we can use its text later on!).

    var e = $(this);
    var title = e.attr("title");
    if(title != '') {
    this.title = '';

    // mouse hover, move and out events
    }

  5. Once the mouse pointer hovers, we need to create the tooltip element, insert the text, hide it in order to make it fade, and then apply the necessary CSS to it (update its position).

    $('<div id="tooltip" />').appendTo("body")
    .text(title)
    .hide()
    .updatePosition(event)
    .fadeIn(400);

  6. Eventually, we might want to create another short function to take care of the update position stuff—since we have to repeat it a couple of times and we have much more control in terms of what we need it to do with less code.

    $.fn.updatePosition = function(event) {
    return this.each(function() {

    $(this).css({
    // we modify the distances by some pixels to make sure
    // the tooltip is visible and put in the best place.
    left: event.pageX+20,
    top: event.pageY-20
    });
    });
    };

  7. As for the events related to the mouse moving out, around, and on the element, we have the following two lines to do the job very smoothly:

    // mouse leaves
    $("#tooltip").remove();
    // mouse moves
    $("#tooltip").updatePosition(event);

  8. Last, but not least, we need to style the tooltip box to make it a little better looking and provide absolute positioning.

    Include the following code into a CSS file named after the plugin (that is, jquery.tooltip.css) and make sure that you link it to the page.

    #tooltip {
    background: #fbf7aa;
    color: #a2844a;
    position: absolute;
    max-width: 150px;
    padding: 5px;
    border: 1px solid #a2844a;
    font-size: 12px;
    }

  9. Our tooltip is finally ready for using, and calling it as we described earlier certainly will work wonders!

  10. And here is the complete code for our plugin. It has been broken down into smaller pieces and functions to make for better looking and more understandable code:

    (function($) {
    $.expr[':'].external = function(object) {
    return(object.hostname != location.hostname);
    };
    $.fn.updatePosition = function(event) {
    return this.each(function() {
    var xy = getPageXY(event);

    $(this).css({
    left: event.pageX+20,
    top: event.pageY-20
    });
    });
    };

    $.fn.tooltip = function() {
    return this.each(function() {
    var e = $(this);
    var title = e.attr("title");

    if(e.is("a") && title != '') {
    e.removeAttr('title')
    .hover(function(event) {
    // mouse hovers
    $('<div id="tooltip" />').appendTo("body")
    .text(title)
    .hide()
    .updatePosition(event)
    .fadeIn(400);
    }, function() {
    // mouse leaves
    $("#tooltip").remove();
    }).mousemove(function(event) {
    // mouse moves
    $("#tooltip").updatePosition(event);
    });
    }
    });
    };
    })(jQuery)

What just happened?

The whole process for getting a (finally) working tooltip plugin should be clear by now. Anyway, here's a quick checklist of what we have done and what needs to be done in order to develop a jQuery plugin similar to ours.

  • Disable the default tooltip display for elements that match our selection and have a title attribute (setting it to an empty string is enough for the tooltip not to appear, but we have to remember to copy the said string to a variable so we can use the text contained afterwards).
  • When the mouse pointer hovers for the first time on a link, a new tooltip division is created. The tooltip box will be appended to the body and will be given absolute positioning. So we can set its distance from the top and left edges and make it appear close to the mouse cursor.
  • As the mouse pointer moves on the link, the tooltip should follow. We thus need to update its top and left values according to the mouse cursor location.
  • Eventually, the mouse will move away from the link and the tooltip should disappear. The whole process will repeat over and over for each link in the page.

Also, a couple more points to discuss are directly related to this script's cross-browser support and further customization of the tooltip.

As for the first, even though we have actually never taken browsers into account until now, we should, of course, do whatever possible to get our plugin working on many different browsers.

This is to our advantage, after all. If the plugin isn't working smoothly in any situation, our web page will not look good, behave right, or do what we thought it would.

Step by step, plugin after plugin, we are slowly adding more and more concepts and code into our plugins. This makes for a more advanced approach to plugin development, taking care of even little imperfections and flaws that our software might have on different browsers.

As for what customization is concerned, not much can be said, actually. The tooltip box is contained in a DIV element and, as such, all the normal CSS rules apply.

With little effort, we can thus obtain a more complex and appealing interface for our plugin—provided we have some skills at CSS writing. Images can be added too, to give the tooltip some shadow or other effects that CSS-only solutions will not allow.

Have a go hero – add options

Finally, the user should be given the opportunity to customize the tooltip plugin according to their needs and liking. So an option-less structure (as it is now) isn't actually the best choice in terms of usability.

It's true that users can include their own CSS file and overwrite every single instruction. However, some tasks, such as making rounded corners, changing the background, and selecting the font color, are more suitable for immediate application directly operating on the code (and thus the function call) rather than going all the way for a separate stylesheet.

Add options to give the user the possibility to change the above-mentioned parameters in a quick and easy way. You should also parameterize the offsets from the cursor and can add, along with rounded corners, the animation used when the tooltip is shown.

Summary

By now the structure lying behind a plugin is rather clear and the points that all of the plugins seem to share come out with no problem whatsoever. This leads to a quicker and more confident approach to plugin development.

During the creation of our tooltip plugin we have faced some problems, for which we have provided some flexible yet direct solutions, thanks to the modularity and object-oriented approach jQuery lets us make use of, as well as the incredible options available to overcome a particular hurdle in many different ways.

Specifically, a function is responsible for retrieving the horizontal and vertical coordinates of the mouse cursor, whereas a method has been designed with the only purpose of updating the tooltip position based on the distances from the top and left edges.

Our plugin main code eventually had the sole goal of merging these features into a single piece of code (that is the plugin itself).

With the successful realization of a working tooltip plugin, our first attempt at getting a better understanding of what a user interface plugin actually is, and how they are supposed to work to increase the overall quality and visual appearance of the web page, has happily concluded.


Further resources on this subject:


jQuery Plugin Development Beginner's Guide Build powerful, interactive plugins to implement jQuery in the best way possible
Published: October 2010
eBook Price: $26.99
Book Price: $44.99
See more
Select your format and quantity:

About the Author :


Giulio Bai

Giulio Bai is a law student living in Italy who spends most of his time toying with stuff that doesn't have anything to do with law.

Even after trying to keep the list of his past achievements as short as possible, the number of projects that he joined in (and that invariably sunk shortly thereafter) makes it hard to narrow down his interests to programming and carousels alone.

It should be made clear that any claim of responsibility for those unfortunate ventures is wholeheartedly rejected – they never had the necessary potential to make it anyway.

Books From Packt


jQuery 1.4 Reference Guide
jQuery 1.4 Reference Guide

jQuery UI 1.7: The User Interface Library for jQuery
jQuery UI 1.7: The User Interface Library for jQuery

CMS Design Using PHP and jQuery
CMS Design Using PHP and jQuery

Learning jQuery 1.3
Learning jQuery 1.3

Joomla! 1.5 JavaScript jQuery
Joomla! 1.5 JavaScript jQuery

WordPress 3.0 jQuery
WordPress 3.0 jQuery

Drupal 6 JavaScript and jQuery
Drupal 6 JavaScript and jQuery

PHP jQuery Cookbook
PHP jQuery Cookbook


Code Download and Errata
Packt Anytime, Anywhere
Register Books
Print Upgrades
eBook Downloads
Video Support
Contact Us
Awards Voting Nominations Previous Winners
Judges Open Source CMS Hall Of Fame CMS Most Promising Open Source Project Open Source E-Commerce Applications Open Source JavaScript Library Open Source Graphics Software
Resources
Open Source CMS Hall Of Fame CMS Most Promising Open Source Project Open Source E-Commerce Applications Open Source JavaScript Library Open Source Graphics Software