In this post I'm going to show you how to implement complex tooltips with jQuery. Our goal is to display image previews when a user hovers certain links with his mouse. To start with, here's the underlying markup structure:
<ul id="gallery"> <li><a href="#"><img src="image-tooltips/spider-web.jpg" alt="Spider Web" /></a></li> <li><a href="#"><img src="image-tooltips/dawn.jpg" alt="Dawn" /></a></li> <li><a href="#"><img src="image-tooltips/grass.jpg" alt="Grass" /></a></li> </ul>
As you can see, this is a basic image gallery. To achieve the final effect of an image preview, we need the following structure that we're going to create with jQuery:
<div class="tooltip"> <img/> <p>Caption</p> </div>
Here are the relevant styles for that structure:
div.tooltip { display: block; width: 450px; padding: 10px 8px; background: #eee; border: 1px solid gray; font-size: small; -moz-border-radius: 6px; -webkit-border-radius: 6px; border-radius: 6px; position: absolute; } div.tooltip img { display: block; margin: 0 auto; } div.tooltip p { margin: 0; padding: 6px 0; text-align: center; font-style: italic; text-transform: uppercase; font-variant: small-caps; }
Absolute positioning is crucial here for positioning the tooltips. And here's the jQuery code:
$(document).ready(function() { $('#gallery li a').each(function() { var $a = $(this); var title = $a.find('img').attr('alt'); var src = $a.find('img').attr('src'); var tooltip = $('<div class="tooltip"/>'); var img = '<img src="' + src + '" />'; var caption = '<p>' + title + '</p>'; tooltip.html(img + caption);; tooltip.appendTo('body').hide(); $a.mouseover(function(e) { var top = e.pageY; var left = e.pageX; tooltip.css({ display: 'block', top: top + 5, left: left + 5 }); }); $a.mouseout(function() { tooltip.hide(500); }); }); });
As you can see, we did build our tooltips using the src
and alt
attributes of each image in the gallery. Then we used the coordinates of the event
object to position our tooltips. You can see this demo
here.
This is excellent! Thank you!
Thanks! :-)