Thanks to the all-encompassing power of Twitter, I was sent a nice little jquery wizard called Glimmer that generates jquery snippets for you (cheers, Jamie!).
Needing a quick tooltip solution, I gave Glimmer’s a whirl, and all was dandy. However, I ran into a small problem where I was creating the tooltip-generating element on the fly with AJAX. When new elements were being created, the tooltip was retaining a previous tooltip’s content.
As the tooltip is displayed by appending the tooltip element (in this case a <p> tag) on mouse over, and hidden by removing the <p> tag on mouse out, there seemed to be instances where the removal of the tooltip element wasn’t being triggered, and so several tooltip elements were being generated, all with the same id ‘tooltip’.
Here, for your coding pleasure, is my quick fix:
$(document).ready(function() {
// initially create the tooltip element (in this case, a simple p tag), and hide it
$('body').append('<p id="tooltip">');
$('#tooltip').hide();
function mouseoverActiontooltip(event) {
// set the tooltip to contain the triggering element's 'alt' attribute (Glimmer used the 'rel' attribute, but you can use what you like), and show it
$('#tooltip').html($(this).attr('alt')).show();
$('#tooltip').css("left",(event.pageX + 20) + "px");
$('#tooltip').css("top",(event.pageY - 10) + "px");
}
function mouseoutActiontooltip(event) {
// on roll out, hide the tooltip, as opposed to completely removing it
$('#tooltip').hide();
}
function mousemoveActiontooltip(event) {
$('#tooltip').css("left",(event.pageX + 20) + "px");
$('#tooltip').css("top",(event.pageY - 10) + "px");
}
// bind the above functions to the triggering element, in this case all img tags
$('img').bind('mouseover', mouseoverActiontooltip);
$('img').bind('mouseout', mouseoutActiontooltip);
$('img').bind('mousemove', mousemoveActiontooltip);
});
Hope this works for you!