Create a jQuery Tooltip!

In this article I am going to show you how to create a simple Tooltip effect using jQuery. What’s great about this method is that it degrades gracefully, so if someone doesn’t have Javascript enabled they don’t see anything out of place.

This tutorial assumes that you have some understanding of jQuery but I’ll be explaining everything as we go so should be good for beginners as well. You will also need to understand HTML and CSS.

I’ve included the finished files and a demo so you can see what we are going to achieve.

The Technique

The tooltip that we will be creating will appear when we hover over a link. We will use the HTML5 custom data attribute (data-*) to hold our information, then use jQuery to dynamically create a container (div) to hold the information within the custom data attribute.

Tutorial Demo

Still not sure what we are trying to achieve? Just click the image below to view the demo:

Create a jQuery Tooltip - Tutorial Demo

The HTML

OK, first create a new HTML file and insert the usual DOCTYPE, html, head, etc. information. Notice I am using the HTML5 DOCTYPE.

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <title>Tooltip Demo</title>
  </head>
  <body>
  </body>
</html>

Add links to your CSS and Tooltip JS files, and create these files. I’ve used layout.css and tooltip.js respectively. You will also need to link to a hosted jQuery library or host your own. I personally prefer to link to Google but use whichever option is best for you and your project.

...
  <head>
    <meta charset="utf-8" />
    <title>Tooltip Demo</title>
    <link rel="stylesheet" href="layout.css" type="text/css" />
    <script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
    <script type="text/javascript" src="tooltip.js"></script>
  </head>
...

Now, add a link (<a href…) with all the usual attributes. I am using the hash symbol (#) because this is a test and I don’t want this link to go anywhere but this script works perfectly with real links.

...
<body>
  <a href="#" title="My Link Title">My Link</a>
</body>
...

Finally, add our custom data attribute. For readability I am using data-tooltip but feel free to use something which better describes your content.

...
<body>
  <a href="#" title="My Link Title" data-tooltip="My Tooltip Text">My Link</a>
</body>
...

And that’s it for the HTML. Pretty simple right? The CSS is even easier…

The CSS

Our tooltip will have an ID of tooltip. This isn’t obvious from the HTML because this div will be created dynamically by our jQuery script, so just take my word for it for now – all will become clear in a minute. For our CSS we actually only need to add two styles to div#tooltip for the basic tooltip effect, position and z-index. Add the following to layout.css:

div#tooltip {
  position: absolute;
  z-index: 10;
}

In the demo (and downloadable files) I’ve also added some basic styling such as background, color, padding and even box shadow to improve the effect, but I’ll leave this up to you to style the tooltip to suit your site design.

The jQuery

Open up tooltip.js and write out the document ready function – feel free to use the shorter version but for readability I will use the full function.

$(document).ready(function() {
});

Next we want to target any element with an attribute of data-tooltip, so this will be our selector. The action will be .hover.

$(document).ready(function() {
  $("[data-tooltip]").hover(
    function() {
    }
  );
});

We first want to create the div which will hold our tooltip information. Remember from above that this will be a div with an ID of tooltip. We will use .before to position this div before our link in the DOM. This is why position and z-index are so important in our CSS – these position the tooltip div visually above our link (and other content) and stops any nasty content jumping from occurring. Note the single quotes used.

$(document).ready(function() {
  $("[data-tooltip]").hover(
    function() {
      $(this).before('<div id="tooltip"></div>')
    }
  );
});

Next we want to get the information from our data attribute and store it in a variable. I have put this variable above the previous line which is good practice, especially in cases where I would be using more than one variable, i.e. keeping them together.

$(document).ready(function() {
  $("[data-tooltip]").hover(
    function() {
      var tooltip = $(this).attr("data-tooltip");
      $(this).before('<div id="tooltip"></div>')
    }
  );
});

Finally, we want to add the information stored in our variable to our new div. We can use .text to achieve this.

$(document).ready(function() {
  $("[data-tooltip]").hover(
    function() {
      var tooltip = $(this).attr("data-tooltip");
      $(this).before('<div id="tooltip"></div>')
      $("div#tooltip").text(tooltip);
    }
  );
});

If you have any basic knowledge of jQuery you will know that .hover also includes hover off within the action. Let’s make use of that now to delete the tooltip div when we move our mouse cursor off the link. We simply need to use .remove to achieve this.

$(document).ready(function() {
  $("[data-tooltip]").hover(
    function() {
      var tooltip = $(this).attr("data-tooltip");
      $(this).before('<div id="tooltip"></div>')
      $("div#tooltip").text(tooltip);
    },
    function() {
      $("div#tooltip").remove();
    }
  );
});

We are almost done. The last part is to get the tooltip div to follow our mouse cursor as it moves around the link. I have used a similar effect in a previous post. First we want to create two variables which will tell the div how far away from our cursor to move so that we can easily see all of the text.

$(document).ready(function() {
  var moveLeft = 20;
  var moveDown = 10;
  $("[data-tooltip]").hover(
    ...
  );
});

The action of the tooltip div moving occurs when we move our mouse cursor around on the link with the data attribute, so this is what we will be targeting with the .mousemove action.

$(document).ready(function() {
  var moveLeft = 20;
  var moveDown = 10;
  $("[data-tooltip]").hover(
    ...
  );
  $("data-tooltip").mousemove(function() {
  });
});

We then just need to use .css on our tooltip div to move it from the top and from the left – remember that we used position: absolute in our CSS, this is coming into play again.

$(document).ready(function() {
  var moveLeft = 20;
  var moveDown = 10;
  $("[data-tooltip]").hover(
    ...
  );
  $("data-tooltip").mousemove(function() {
    $("div#tooltip").css('top', e.pageY + moveDown).css('left', e.pageX + moveLeft);
  });
});

We have one small update to do to our code to finish. Notice the e used  - i.e. e.pageY and e.pageX. We simply need to add e between the parenthesis of each of our functions. See the full complete code below:

$(document).ready(function() {
  var moveLeft = 20;
  var moveDown = 10;
  $("[data-tooltip]").hover(
    function(e) {
      var tooltip = $(this).attr("data-tooltip");
      $(this).before('<div id="tooltip"></div>')
      $("div#tooltip").text(tooltip);
    },
    function(e) {
      $("div#tooltip").remove();
    }
  );
  $("[data-tooltip]").mousemove(function(e) {
    $("div#tooltip").css('top', e.pageY + moveDown).css('left', e.pageX + moveLeft);
  });
});

Load up your HTML page and check out the script in action.

That’s it!

Create a jQuery Tooltip - Tutorial Demo

Get The Source Code

You can download the complete tutorial source code by clicking on the big button below and unzipping the file.

This entry was posted in jQuery, Tutorials

Don't forget to share!
If you liked this post, please share it with your friends - Thanks!

Your Comments

  1. Howdy just wanted to give you a quick heads
    up. The words in your article seem to be running off the screen in Safari.

    I’m not sure if this is a formatting issue or something to do with internet browser compatibility but I thought I’d post
    to let you know. The style and design look great though!
    Hope you get the issue solved soon. Many thanks

    • Lucas says:

      Hi Laura,Good Example for the Pop up window with div tag but i have one adtaidonil requirement with this So i need your help on this.when user hover on the link the pop up should display and when user hover out the link pop up should become invisible but when a user roll over the pop up, the pop up should remain visible and when rolling out from pop up it should become invisble So these are the two scenarios need to be implemented.1.when user roll out from the link and does not roll over the pop up then pop up should become invisble.2. when user roll out from the link and if he roll over the pop up window so it should remain visible and after rolling out from pop up window it should become invisible.Your help is appreciated

  2. Do you have any video of that? I’d care to find out
    some additional information.

  3. Lelala says:

    Thanks, by examining your code, i found the bug in my homegrown solution :-)
    Regards

  4. Flat Design says:

    Thx for ur code, but i think there are already too many solutions for this.

  5. Laura you article rocks! See I am just a web design guy in South Florida, work for a web design firm that provides more internet marketing than coding, though the are experts at email marketing and lead generation. Think we are always looking for skilled programmers who are looking to do side work. Anyway, our site is tombecksmedia.com and our number is 561-983-1434 talk to you sometime.

  6. Patrick says:

    Awesome! Thanks for sharing !

  7. William says:

    Great article …Thanks for your great information, the contents are quiet interesting. Thank You for sharing your important information.

Leave a Reply to sterkly revenue suite Cancel 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>