javascript

Create a simple tooltip with jQuery

Create your own basic tooltip with jQuery – no plugin required

If you only need a simple text based tool tip style to enhance the effect when someone hovers over a link, you can create your own lightweight jQuery without the need to use a jQuery plugin.

Here’s the HTML you’ll need:

<a href="#" title="Check out Code Chewing &gt;">Code Chewing</a>

And now some basic CSS to give it an appearance you won’t normally see inside the standard browser’s tooltip:

.tooltip {
  display:none;
  position:absolute;
  border-radius:5px;
  box-shadow:2px 2px 3px rgba(0,0,0,.2);
  background-color:#CCC;
  border:1px solid #F7F7F7;
  text-shadow:-1px -1px 0 #F4F4F4;
  color:#666;
  font:bold italic 16px Tahoma, Geneva, sans-serif;
  padding:10px;
}

And here’s the jQuery/JavaScript (remember to attach a jQuery library):

$(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');

 });

});

And now you have a simple tool tip, without the use of a plugin!

This entry was posted in JavaScript, jQuery on by Peter J Langley.

9 thoughts on “Create a simple tooltip with jQuery

  1. Mehul

    Thanks a lot bro very nice code….but i m having prob tooltips are hide inside other href link(Other css) how to solve it

    Reply
    1. Peter J Langley Post author

      Hi and thanks for your feedback.

      I’m not sure that I fully understand your query – are you saying you’re getting tooltips on anchor elements you don’t want tooltips triggering from?

      Reply
  2. Felis

    Thank you, Peter. This is really lightweight and helpful!
    Just a small addition for people who don’t want every tooltip to be styled that way:
    You can assign a class to your a-tag, let’s say ‘tip’, like so <a href=”#” title=”some text to be displayed on hover” rel=”nofollow” class=”tip”>hover me</a>
    To make that work, change first line of script from
    $(‘a’).hover(function(e){ // Hover event
    to
    $(‘a.tip’).hover(function(e){ // Hover event

    Reply

Leave a Reply

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

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>