jQuery: social icons with tooltips

Today social icons are a must for every good web site. In this post I'm going to show you how to create dynamic tooltips to be displayed together with such icons by using jQuery and CSS. First of all, we need an unordered HTML list that will contain our social icons. These icons will be set as background images for each link contained in our list. Our HTML is as follows:

<ul id="social">
<li><a href="#" id="facebook" title="Add to Facebook">Facebook</a></li>
<li><a href="#" id="google" title="Add to Google">Google</a></li>
<li><a href="#" id="delicious" title="Add to Delicious">Delicious</a></li>
</ul>

And these are our CSS styles:

#social {
	width: 86px;
	height: 25px;
	margin: 0;
	padding: 0;
	list-style: none;
	position: relative;
}

#social li {
	width: 25px;
	height: 25px;
	float: left;
	margin-right: 3px;
}

#social li a {
	float: left;
	display: block;
	width: 100%;
	height: 100%;
	text-indent: -1000em;
	background-repeat: no-repeat;
	text-decoration: none;
}

#social #facebook {
	background-image: url(social-icons/facebook.png);
}
#social #google {
	background-image: url(social-icons/google.png);
}
#social #delicious {
	background-image: url(social-icons/delicious.png);
}

span.tooltip {
	background: #fe6;
	padding: 5px;
	display: block;
	width: 120px;
	border: 1px solid #c40;
	border-radius: 6px;
	position: absolute;
	color: #333;
	text-indent: 0;
	font: small Arial, sans-serif;
	text-align: center;
}

Our tooltip will be inserted in each link and then hidden. When a user hovers a link, the tooltip will be shown and absolutely positioned just above the social icon. Here's our jQuery code:

$(document).ready(function() {

    $('#social li').each(function() {

        var $li = $(this);
        var title = $li.find('a').attr('title');

        $li.find('a').removeAttr('title');

        $('<span class="tooltip"/>').text(title).appendTo($li.find('a')).hide();

    	$li.find('a').mouseover(function() {

    	    var top = $(this).position().top - 30;
    	    var left = $(this).position().left;

    	    $(this).find('span').fadeIn().animate({
    	      top: top,
    	      left: left
    	    }, 'slow'); 

    	});

    	$li.find('a').mouseout(function() {

    	    $(this).find('span').fadeOut('slow');

    	});

    });

});

We use the x and y coordinates of each link to exactly position our tooltips. You can see the demo below.

Demo

Live demo

This entry was posted in by Gabriele Romanato. Bookmark the permalink.

Comments are closed.