WordPress Code Snippets

A fresh mix of code snippets and tutorials

Simple jQuery tooltip

82

There are many great jQuery plugins for creating tooltips, but for simple cases only a few lines of code are needed.

To display link title attributes as a “fancy tooltip”, add this slice of jQuery:

// simple tooltips
$(document).ready(function(){
	$('a').hover(function(e){ // Hover event
		var titleText = $(this).attr('title');
		$(this).data('tiptext', titleText).removeAttr('title');
		$('<p class="tooltip"></p>').text(titleText).appendTo('body').css('top', (e.pageY - 10) + 'px').css('left', (e.pageX + 20) + 'px').fadeIn('slow');
	}, function(){ // Hover off event
		$(this).attr('title', $(this).data('tiptext'));
		$('.tooltip').remove();
	}).mousemove(function(e){ // Mouse move event
		$('.tooltip').css('top', (e.pageY - 10) + 'px').css('left', (e.pageX + 20) + 'px');
	});
});

Then add this CSS, customizing to suit your needs:

.tooltip {
	display: none; position: absolute; padding: 10px;
	color: #777; background-color: #fff; border: 1px solid #777; 
	box-shadow: 0 1px 3px 1px rgba(0,0,0,0.5); border-radius: 3px;
	}

Note for this to work, jQuery must be included on the page, for example:

<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"></script>

You can see an example of this technique applied here at WP-Mix for the left/right navigation buttons (hover and see!).

Source


Show Support

Like our new Facebook Page to show support!