Tooltip Image with Mootools

Posted by Sean on Dec 12, 2008 under Javascript

Compatible with Mootools v1.2

Alright, taking a look at the Mootools docs, and playing around, I've quickly learnt how to throw an image into a Tooltip with Mootools.  It's far easier, and far cleaner than what I was doing with version 1.1.  The first way still works, and the validator tells me its valid, but it feels dirty.

A little background: the tooltip is built from the title and rel (or href if rel is empty) attributes of the element.

Putting <img> in the rel property

window.addEvent('domready',function() {
var t = new Tips('.tip');
});
<a class="tip" href="http://mootools.net/" rel="<img src=mootools_white.jpg />" title="Mootools.net">Mootools</a>

This was my original, dirty way.  It should still work.  Make sure to escape the left and right brackets inside the rel property, or you've got invalid XHTML. So if that looks like your bag of goodies, take it.  For those who like feeling good inside, here's a newer, cleaner way of doing things.

Using Element.store to store an image

The Mootools Tips class use Element.store and Element.retrieve for the tool-tips title and text, so that means we can override the defaults.  It just requires a little more scripting, but I think that's perfectly fine.

The benefit here is that you can make a new DOM Element of an image, and store the image into the tip:text field of the Element. Take a peek:

window.addEvent('domready',function() {
var t = new Tips('.tip');

$$('.tip').each(function(tip){
var imgSrc = tip.retrieve('tip:text');
var imgAlt = tip.retrieve('tip:title');
tip.store('tip:text', new Element('img',{'src':imgSrc,'alt':imgAlt}));
});
});

This way, we can store the filename of the image in the rel property, and then construct the image with Javascript.  Feels a whole lot cleaner than keeping an escaped img tag inside a property.

<a class="tip" href="#" rel="mootools_white.jpg" title="Mootools.net">Mootools</a>

There it is.  Let me know if I goofed in my write-up.  And subscribe if you felt this was useful.

One Comment

  1. Gravatar
    Rob V Jun 12, 2009

    Hey man - nice work - great tip. Was looking to do the exact same thing.
    Funny thing my first attempt was exactly like yours, didnt even think about using store.

Add a Comment

Search

Treats

  • David DeSandro

    Design blog where the articles have different designs, similar to Jason Santa Maria. Talks a bit about Canvas, and uses some Javascript animations for the navigation.
  • policy for polling rss

    Some good policies if you plan on building an RSS reader, how often to poll, check for last modified, and so forth.
  • MooTools Singletons Using Events Mixin

    Aaron shows how he makes a Singleton using 'new Events()', which allows other classes to tell the Singleton to fireEvents, keeping other classes ignorant of each other.
See all »