Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Save more on your purchases! discount-offer-chevron-icon
Savings automatically calculated. No voucher code required.
Arrow left icon
All Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Newsletter Hub
Free Learning
Arrow right icon
timer SALE ENDS IN
0 Days
:
00 Hours
:
00 Minutes
:
00 Seconds

jQuery User Interface Plugins: Tooltip Plugins

Save for later
  • 6 min read
  • 27 Oct 2010

article-image

 

jQuery Plugin Development Beginner's Guide




jquery-user-interface-plugins-tooltip-plugins-img-0

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:

jquery-user-interface-plugins-tooltip-plugins-img-1

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:

jquery-user-interface-plugins-tooltip-plugins-img-2

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/).

Unlock access to the largest independent learning library in Tech for FREE!
Get unlimited access to 7500+ expert-authored eBooks and video courses covering every tech area you can think of.
Renews at ₹800/month. Cancel anytime

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):

jquery-user-interface-plugins-tooltip-plugins-img-3

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.