Customizing Tooltips Using jQuery

Here is a simple code on  how you could customize your tooltips using jQuery.

The idea here is to use the <label> tag as the custom tooltip for our links. The id of our <a> is the same value as the “for” attribute of the <label> tag. In this way, we have created a relationship between the<a> tag and <label> tag.

Here is the Live Demo of this script.

Demo

The script supports:

  • Plain text tooltips
  • HTML Formatted text
  • Tooltips with images

HTML head

First, we must include the latest jQuery inside our <head></head> tags.
{code type=”php”}<script type=”text/javascript” src=”jquery-1.3.2.min.js”></script>{/code}

CSS

Then, let us add some styling to our tooltips.
{code type=”php”}.tooltip label{
margin-left:10px;
display:none;
border:solid 1px #7DA7D9;
padding:5px;
background-color:#ffffff;
position:absolute;
}{/code}

HTML body

Next, i would be using <ul> as the container for our links.
{code type=”php”}<ul class=”tooltip”>
<li>
<a href=”#link1″ id=”link1″>Link 1</a>
<label for=”link1″>This is the tooltip for “Link 1″</label>
</li>
<li>
<a href=”#link2″ id=”link2″>Formatted Tooltip</a>
<label for=”link2″>
<em>This</em> is a <br /><strong>formatted</strong>
<span style=”color:red;”>tooltip</span>
</label>
</li>
<li>
<a href=”#link3″ id=”link3″>Image in tooltip</a>
<label for=”link3″>
<img src=”http://lorempixel.com/300/150/food/1/” />
</label>
</li>
<li>
<a href=”#link4″ id=”link4″>Image in tooltip 2</a>
<label for=”link4″>
<img src=”http://lorempixel.com/300/150/food/2/” />
<br />
Another tooltip with image
</label>
</li>
</ul>{/code}

jQuery Script

Finally, we add our jQuery script. Whenever a user hovers his mouse over link, the script would use the link id to search for label that is related to our link using the for attribute in the <label> tag. I used the show() function to make the label visible when hovering and the hide() function to hide it.
{code type=”php”}<script type=”text/javascript”>
$(“.tooltip a”).mouseover(function(){
$(‘label[for=”‘ + $(this).attr(“id”) + ‘”]’).show();
}).mouseout(function(){
$(‘label[for=”‘ + $(this).attr(“id”) + ‘”]’).hide();
});
</script>{/code}

Recommended Posts