JQuery Tooltip

Ever in need of more than just the standard abbr tooltip? A little while back I wrote just that. It can easily be made prettier, but it works as intended. What this does is listening for the mouseover and mouseout events and display a div with absolute positioning at the element’s location with the tooltip text.

To add tooltips, the syntax would be like this:

<a href="#" class="tooltip" data-title="Tooltip title" 
    data-content="Tooltip text">The text you want tooltipped</a>

This is what is looks like in action:

Tooltip title and text

The JavaScript code that does the work looks like this. As you can see, the listeners are registered and when the mouse hovers the element, it gets the data-title and data-content attributes from the <a> element.

$(document).ready(function() {
    $('a.tooltip').mouseover(function(e) {
        var title = $(this).attr('data-title');
        var content = $(this).attr('data-content');
		
        if(title != null && title.length > 0) {
            $('div#tooltip_content').html("<b>" + title);
			
            if(content != null && content.length > 0) {
                $('div#tooltip_content').append("</b><br /><br />" + content);
            }
		
        } else if(content != null && content.length > 0) {
            $('div#tooltip_content').append(content);
		
        } else {
            return;
        }

        $('div#tooltip_wrapper').css('left', $(this).position().left + 
            ($(this).width() / 4));
        $('div#tooltip_wrapper').css('top', $(this).position().top + 
            $(this).height());
        $('div#tooltip_wrapper').show();
    });
	
    $('a.tooltip').mouseout(function(e) {
        $('div#tooltip_wrapper').hide();
        $('div#tooltip_content').html("");
    });
});



The full source code can be found here: jquery_tooltip.html.
As always: If you have any questions, please let me know!

Leave a Reply

Your email address will not be published. Required fields are marked *