Simple jQuery Tooltip

Here's a super easy jQuery Tooltip snippet.

Customize the JavaScript and CSS to fit your needs!

JavaScript

Notice we're looking for the link titles.

You could change it to look for a specific class or html tag.

$(document).ready(function(){ $('a').hover(function(e){ 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(){ $(this).attr('title', $(this).data('tiptext')); $('.tooltip').remove(); }).mousemove(function(e){ $('.tooltip').css('top', (e.pageY - 10) + 'px').css('left', (e.pageX + 20) + 'px'); }); });

CSS

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

Full HTML

<!DOCTYPE html> <head> <meta charset="utf-8"> <title>Demo: <a href="https://ricard.dev/simple-jquery-tooltip/">Simple jQuery Tooltip</a> | Codeground</title> <style> body{ margin:50px; font-size:20px; font-family: 'Trebuchet MS', Verdana, Arial;} .tooltip { display: none; position: absolute; padding: 10px; color: black; background-color: red; border: 1px solid black; box-shadow: 0 1px 3px 1px rgba(0,0,0,0.5); border-radius: 3px; } </style> </head> <body> <a title="This is the tooltip content">Hover me!</a> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script> <script> $(document).ready(function(){ $('a').hover(function(e){ 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(){ $(this).attr('title', $(this).data('tiptext')); $('.tooltip').remove(); }).mousemove(function(e){ $('.tooltip').css('top', (e.pageY - 10) + 'px').css('left', (e.pageX + 20) + 'px'); }); }); </script> </body> </html>

Demo

View Demo

2 comments
  • Hi,
    How do I apply its tooltip solution to more than one element?
    For example, for images, inputs and other elements that may receive the title attribute.

    • Hello,

      As you can see in the code, we’re using a jQuery selector for “a” (links). From the example:

      $('a').hover(function(e){ ....

      Instead, use any selector you might need:

      $('.my-custom-class')... $('a, img, input')...

Leave a Reply

Add <code> Some Code </code> by using this tags.

*
*