Simple tooltip - jQuery plugin

A few weeks ago I needed to display a tooltip for a field in a form. There are lots of jQuery plugins for that but I just needed a simple one. I wanted to display a message on mouseover. Since I thought it is very easy to do it myself, I started to work on it. After a few minutes, it was ready.

Demo

Display tooltip on mouseover

How to use

$("#some-element").simpletooltip()
or
$("a.some-class").simpletooltip()

Caution

The text displayed in tooltip is the same as the TITLE attribute of the element.

Download

Click here to download the simpletooltip jquery plugin.

Additional Info

  • Tested with IE 6+, Firefox 3, Safari 4 and Opera 9
  • jQuery 1.3.2 (it should work with previous releases of jQuery, but I didn't test it) 

Changelog

v1.1

  • tooltip flips to the left/top of the cursor if it goes out of the screen. Now it is always displayed on the visible area

v1.0

  • display a tooltip on mouseover

class Vs ID

Good job.
I was looking for a simple tooltip like this.
Anyway, I think it could be more useful if we can call it with a class name on the a tag, instead of an id.
Just because it is very boring to set an id on every single link of a page.
I've tryed to use it with class name ( $('a.tooltip').simpletooltip(); ), but unfortunately it gives back on every link always the same title, the one of the first ".tooltip" a tag.

Have you any idea about how to fix this behavior?

Cheers,
m.

[RE] class Vs. ID

First of all, thanx for your feedback.

I wanna tell you that I fixed that. If you download this plugin again, it should work just fine. Unfortunately, I had to remove the ability to manually set the tooltip text. Now it only displays the element TITLE as a tooltip. But I'll try to make it work again.

Cheers,
Marius

Simpletooltip

Very nice plugin, could do with a few config options though such as an offset from pointer :D

tooltip options

I was thinking of that but when I created this, I wanted something very simple and quick. If I'll have the time, I might work on this. What config options would you be interested in?

finally!

a small and simple no-frills tooltip. thanks for sharing.
will adapt for a few custom needs - in particular, inserting my own div content. passing in an id or a jquery object as the content could be an option perhaps. can't always rely on a title attribute, etc.
fixed positioning might be a nice option too.

.simpletooltip(param) ignores param

Hello!

"Usage instructions" in README.txt suggest two options:
1. if the element has a TITLE attribute:
$("#some-element").simpletooltip();
2. if the element doesn't have a TITLE attribute or you want to override the TITLE attribute:
$("#some-element").simpletooltip("Tooltip text to display");

2nd doesn't work but it's very easy to fix.

Cheers, and thanks for nice, simple plugin.

[RE] .simpletooltip(param) ignores param

Yeah, I know about that. Sorry, I had to make some changes and I removed the param but I forgot to update the README.txt file.

fix to flip if too close to screen edges

I really like the simplicity of this, however I wanted it to flip to the left/top of the cursor if it got too close to the right/bottom of the screen. a small change to the code acheives this, thought I'd share it back to you.
(function($){
    $.fn.simpletooltip = function(){
        return this.each(function() {
          var text = $(this).attr("title");
          $(this).attr("title", "");
          if(text != undefined) {
            $(this).hover(function(e){
                $(this).attr("title", "");
                $("body").append("" + text + "");
                $("#simpleTooltip").css( $.fn.simpletooltip.edge(e.pageX,e.pageY) ).fadeIn("medium");
            }, function(){
                $("#simpleTooltip").remove();
                $(this).attr("title", text);
            });
            $(this).mousemove(function(e){
                $("#simpleTooltip").css( $.fn.simpletooltip.edge(e.pageX,e.pageY) ).fadeIn("medium");
            });
          }
        });
    };
    $.fn.simpletooltip.edge = function(pageX,pageY){
        /* Set your tolerance here! */      
        var tolerance = {x:200,y:100};
        var $w = $(window);
        //work out pageX relative to window (i.e. take scroll into account.)
        var screenPos = {x:pageX-$w.scrollLeft(), y:pageY-$w.scrollTop()};
        var css = {};
        if( $w.width() - screenPos.x <= tolerance.x ){
          css.right = ($(document).width()-pageX);
          css.left = null;
        }else{
          css.left = pageX+12;
          css.right = null;
        }

        if( $w.height() - screenPos.y <= tolerance.y ){
          css.bottom = ($(document).height()-pageY);
          css.top = null;
        }else{
          css.top = pageY+12;
          css.bottom = null;
        }
        return css;
    };
})(jQuery);

Thanks for your work!

[RE] fix to flip if too close to screen edges

Based on your ideea I made some changes. I kept your ideea but I did it my way, as simple as possible.

Very nice plugin, could do

Very nice plugin, could do with a few config options though such as an offset from pointer :DD

How can I load a tooltip on

How can I load a tooltip on demand?

I have a JS function that returns some html using ajax, when the ajax call is completed I want to show the data in tooltip.

Thanks

Options

Great script, thanks for releasing this. I love the small footprint and KISS principle, but I miss having options to override some defaults, like so:

$(".tooltip").simpletooltip({
followCursor: false,
fadeSpeed: 'fast',
xOffset: 10,
yOffset: 10,
tooltipID: '#simpleTooltip'
});

So I modified it a little bit (nothing too fancy). Thought it be nice to share it here, perhaps it's of use to anyone.

(function($){ $.fn.simpletooltip = function(options){
options = jQuery.extend({
followCursor: true,
fadeSpeed: "medium",
xOffset: 12,
yOffset: 12,
tooltipID: 'simpleTooltip'
}, options);
return this.each(function() {
var text = $(this).attr("title");
$(this).attr("title", "");
if(text != undefined) {
$(this).hover(function(e){
var tipX = e.pageX + options.xOffset;
var tipY = e.pageY + options.yOffset;
$(this).attr("title", "");
$("body").append("" + text + "");
if($.browser.msie) var tipWidth = $("#"+options.tooltipID).outerWidth(true)
else var tipWidth = $("#"+options.tooltipID).width()
$("#"+options.tooltipID).width(tipWidth);
$("#"+options.tooltipID).css("left", tipX).css("top", tipY).fadeIn(options.fadeSpeed);
}, function(){
$("#"+options.tooltipID).remove();
$(this).attr("title", text);
});
if (options.followCursor == true) {
$(this).mousemove(function(e){
var tipX = e.pageX + options.xOffset;
var tipY = e.pageY + options.yOffset;
var tipWidth = $("#"+options.tooltipID).outerWidth(true);
var tipHeight = $("#"+options.tooltipID).outerHeight(true);
if(tipX + tipWidth > $(window).scrollLeft() + $(window).width()) tipX = e.pageX - tipWidth;
if($(window).height()+$(window).scrollTop() < tipY + tipHeight) tipY = e.pageY - tipHeight;
$("#"+options.tooltipID).css("left", tipX).css("top", tipY).fadeIn(options.fadeSpeed);
});
}
}
});
}})(jQuery);

Thanks again!

Thought you might like to

Thought you might like to know that after submitting my comment, Drupal showed the following message at the top of the page:

Unable to send e-mail. Please contact the site admin, if the problem persists.

Well... let's make it more Generic...

First of all, you've done a great work!!!

Second, i have a sugestion...
On line number 9 (jquery.tooltip.v.1.1.js), i thing you could insert: "if ($(this).attr("title").length > 0) {" and make the script more generic...
doing this, we can define the start script for every tag without get an empty box for those tag that don't have titles declared...
Example:
$("img").simpletooltip();
$("a").simpletooltip();
$("input").simpletooltip();
$("select").simpletooltip();

Sorry about the english... i'm from Brazil...

Hugs.

Esti tare bai! :p

Esti tare bai! :p

Good plugin! Thanks! But I'm

Good plugin! Thanks! But I'm found small bug.

When text in tooltip very big, tooltip scrolled out.

See the screen http://ipicture.ru/Gallery/Viewfull/18089312.html

well, this is supposed to be

well, this is supposed to be a very simple and light tooltip plugin. Also it was my first jquery plugin. If you really need it, I can make some changes to correct that.

nice script man, thanks!

nice script man, thanks!

Just wanted to say a quick

Just wanted to say a quick thanks for this plugin - very simple and lightweight! Thanks!

Is it free? License type?

Is it free? License type?

Yes, it's free

It's free. You can use it as you wish.

to avoid IE6 overlap bug with

to avoid IE6 overlap bug with select element use jquery.bgiframe plugin and insert line
$("#"+options.tooltipID).bgiframe();
after
$("body").append("" + text + "");

multiple event

i need to set multiple event in input box. Ex : focus,hover,click

cnc

Thanks a lot, this will surely prove to be extremely useful!

Here's some help with application/xhtml+xml and meta characters

Greetings, and thank you for the nice simple application of tooltips.
I had a problem with characters like & (& or &) which is not
terribly uncommon. So in an attempt to keep my content truly XHTML
(application/xhtml+xml) && != text/html (tag soup) I had to figure out
how to do some inline string replacement (regex). Here's what I got
to work:
replace

var text = $(this).attr("title");

with

var text = $(this).attr("title").replace(/&/g,'&');

Just add (append) all the replacements you like thusly:


.replace(/>/g,'>').replace(/
This may not be the most efficient approach (should have created a function())
but it worked. :)

OK your blog buggers up everything inside the <code> tags.

So to replace all every ampersand correctly formated as:
(ampersand)#38(semicolon), or (ampersand)amp(semicolon)
with an ampersand (&)
do:
.replace(/&/g,'&');

GAH! sorry, looks like I am unable to help. This blog is about
CODE, but it's not possible to put any in this editor, because
it has no idea how to parse it - even when you use the CODE tag,
or use entities.

Oh well, I tried. ;(

--GW

Images/Alt

To use alt tag in images use following modification:

(function($){ $.fn.simpletooltip = function(){
return this.each(function() {
var text = $(this).attr("title");

// If there are no title-tag (Images) use alt-tag
var attrText = "title";
if (text == "") {
text = $(this).attr("alt");
}

$(this).attr(attrText, "");
if(text != "") {

$(this).hover(function(e){
var tipX = e.pageX + 20;
var tipY = e.pageY + 15;
$(this).attr(attrText, "");
$("body").append("" + text + "");
if($.browser.msie) var tipWidth = $(",simpleTooltip").outerWidth(true)
else var tipWidth = $(".simpleTooltip").width()
$(".simpleTooltip").width(tipWidth);
$(".simpleTooltip").css("left", tipX).css("top", tipY).fadeIn("medium");
}, function(){
$(".simpleTooltip").remove();
$(this).attr(attrText, text);
});
$(this).mousemove(function(e){
var tipX = e.pageX + 20;
var tipY = e.pageY + 15;
var tipWidth = $(".simpleTooltip").outerWidth(true);
var tipHeight = $(".simpleTooltip").outerHeight(true);
if(tipX + tipWidth > $(window).scrollLeft() + $(window).width()) tipX = e.pageX - tipWidth;
if($(window).height()+$(window).scrollTop() < tipY + tipHeight) tipY = e.pageY - tipHeight;
$(".simpleTooltip").css("left", tipX).css("top", tipY).fadeIn("medium");
});
}
});
}})(jQuery);

// Execute
$(document).ready(function(){
$(".jQTooltip").simpletooltip();
});

New improved Version :)

Hello Marius!

I really liked this plugin but while using it, I found that I can further simplify your code. Also I have added few options:

  1. /**
  2.  * jQuery simpleTooltip plugin
  3.  *
  4.  * @author Marius ILIE (http://dev.mariusilie.net) / Improved by Aamir Afridi (http://www.aamirafridi.com - info@aamirafridi.com)
  5.  * @date 2009-08-06
  6.  * @example $("link").simpletooltip({html : 'My Tooltip', mouseOffset.x : 10 , mouseOffset.y : 12})
  7.  * @example $("link").simpletooltip({ opacity : 0.8, css : { 'padding' : '8px' , 'border' : '2px solid #ccc' } })
  8.  * @desc create a tooltip effect for any html element's title attribute or any text provided
  9.  *
  10.  * @name simpletooltip
  11.  * @type jQuery
  12.  * @param String - html - custom text which will overwrite the text in element's title attribute
  13.  * @param String - errorText - text which will appear if there is no title attribute found or html provide to the plugin otherwise leaving this empty will diable the plugin
  14.  * @param Number - cornerRadius - the radius of the round corner of the tooltip. Work only on Firefox 3+ and Webkit-base browsers
  15.  * @param String - cssClass - if provided, It will overwrite any css provided to the plugin
  16.  * @param Number - opacity - the transparency of the tooltip. From 0.0 to 1. Should work on IE but haven't tested
  17.  * @param String - fadeSpeed - the animation speed of the tooptip to fadeIn
  18.  * @param Number  - mouseOffset.x - the position of the tooltip on x-axis
  19.  * @param Number  - mouseOffset.y - the position of the tooltip on y-axis
  20.  * @param Array  - css - css properties will be applied on the tooltip
  21.  * @cat Plugin
  22.  */
  23.  
  24.  
  25.  
  26. (function($,options){ $.fn.simpletooltip = function(){
  27.         var      o = $.extend({}, $.fn.simpletooltip.defaults, options);
  28.         return this.each(function() {                                    
  29.                 var text = ($(this).attr("title")!='') ? $(this).attr("title") : o.errorText, st;
  30.                 if(o.html=='' && text=='') return;
  31.                 $(this).hover(function(e){
  32.                         $(this).attr("title", "");
  33.                         var tipX = e.pageX + o.mouseOffset.x,
  34.                                 tipY = e.pageY + o.mouseOffset.y;
  35.                                   st = $('<div></div>')
  36.                                         .appendTo('body')
  37.                                         .html(($.trim(o.html)!='') ? o.html : text)
  38.                                         .fadeIn(o.fadeSpeed);
  39.                                 if(o.opacity!=1) st.attr('style','opacity:'+o.opacity+'; filter:alpha(opacity = '+o.opacity*100+')');
  40.                                 if($.trim(o.cssClass)!='') st.addClass(o.cssClass)
  41.                                 else st.css($.extend({}, {'position':'absolute','z-index':100,'display':'none','-moz-border-radius'     :o.cornerRadius,'-webkit-border-radius' :o.cornerRadius,'left':tipX,'top':tipY+o.css}, o.css));
  42.                 }, function(){
  43.                         st.remove();
  44.                         $(this).attr("title", text);
  45.                 })
  46.                 .mousemove(function(e){
  47.                         var tipX = e.pageX + o.mouseOffset.x,
  48.                                 tipY = e.pageY + o.mouseOffset.y,
  49.                                 tipWidth = st.outerWidth(true),
  50.                                 tipHeight = st.outerHeight(true);
  51.                         if(tipX + tipWidth > $(window).scrollLeft() + $(window).width()) tipX = e.pageX - tipWidth;
  52.                         if($(window).height()+$(window).scrollTop() < tipY + tipHeight) tipY = e.pageY - tipHeight;
  53.                         st.css({'left':tipX,'top':tipY}).fadeIn(o.fadeSpeed);
  54.                 });
  55.          });
  56.         }
  57.        
  58.         $.fn.simpletooltip.defaults = {
  59.                 html            : '',
  60.                 errorText       : '<b>Error:</b><br />No title attribute found<br />And no Html provide to the plugin.', //Leave it empty which will show nothing
  61.                 cornerRadius: 5,        
  62.                 cssClass        : '',
  63.                 opacity         : 0.9,
  64.                 fadeSpeed       : 'fast',
  65.                 mouseOffset: {
  66.                                                 x : 10,
  67.                                                 y : 10
  68.                                           },
  69.                 css                     : {
  70.                                                 'padding'       : 7,
  71.                                                 'background': '#F2F3F5',
  72.                                                 'border'        : '1px solid #A6A7AB',
  73.                                                 'width'         : '140px',
  74.                                                 'font-size'     : '12px'
  75.                                           }
  76.         };
  77.        
  78. })(jQuery);

New improved Version :)

Hello Marius!

I really liked this plugin but while using it, I found that I can further simplify your code. Also I have added few options:

  1. /**
  2.  * jQuery simpleTooltip plugin
  3.  *
  4.  * @author Marius ILIE (http://dev.mariusilie.net) / Improved by Aamir Afridi (http://www.aamirafridi.com - info@aamirafridi.com)
  5.  * @date 2009-08-06
  6.  * @example $("link").simpletooltip({html : 'My Tooltip', mouseOffset.x : 10 , mouseOffset.y : 12})
  7.  * @example $("link").simpletooltip({ opacity : 0.8, css : { 'padding' : '8px' , 'border' : '2px solid #ccc' } })
  8.  * @desc create a tooltip effect for any html element's title attribute or any text provided
  9.  *
  10.  * @name simpletooltip
  11.  * @type jQuery
  12.  * @param String - html - custom text which will overwrite the text in element's title attribute
  13.  * @param String - errorText - text which will appear if there is no title attribute found or html provide to the plugin otherwise leaving this empty will diable the plugin
  14.  * @param Number - cornerRadius - the radius of the round corner of the tooltip. Work only on Firefox 3+ and Webkit-base browsers
  15.  * @param String - cssClass - if provided, It will overwrite any css provided to the plugin
  16.  * @param Number - opacity - the transparency of the tooltip. From 0.0 to 1. Should work on IE but haven't tested
  17.  * @param String - fadeSpeed - the animation speed of the tooptip to fadeIn
  18.  * @param Number  - mouseOffset.x - the position of the tooltip on x-axis
  19.  * @param Number  - mouseOffset.y - the position of the tooltip on y-axis
  20.  * @param Array  - css - css properties will be applied on the tooltip
  21.  * @cat Plugin
  22.  */
  23.  
  24.  
  25.  
  26. (function($,options){ $.fn.simpletooltip = function(){
  27.         var      o = $.extend({}, $.fn.simpletooltip.defaults, options);
  28.         return this.each(function() {                                    
  29.                 var text = ($(this).attr("title")!='') ? $(this).attr("title") : o.errorText, st;
  30.                 if(o.html=='' && text=='') return;
  31.                 $(this).hover(function(e){
  32.                         $(this).attr("title", "");
  33.                         var tipX = e.pageX + o.mouseOffset.x,
  34.                                 tipY = e.pageY + o.mouseOffset.y;
  35.                                   st = $('<div></div>')
  36.                                         .appendTo('body')
  37.                                         .html(($.trim(o.html)!='') ? o.html : text)
  38.                                         .fadeIn(o.fadeSpeed);
  39.                                 if(o.opacity!=1) st.attr('style','opacity:'+o.opacity+'; filter:alpha(opacity = '+o.opacity*100+')');
  40.                                 if($.trim(o.cssClass)!='') st.addClass(o.cssClass)
  41.                                 else st.css($.extend({}, {'position':'absolute','z-index':100,'display':'none','-moz-border-radius'     :o.cornerRadius,'-webkit-border-radius' :o.cornerRadius,'left':tipX,'top':tipY+o.css}, o.css));
  42.                 }, function(){
  43.                         st.remove();
  44.                         $(this).attr("title", text);
  45.                 })
  46.                 .mousemove(function(e){
  47.                         var tipX = e.pageX + o.mouseOffset.x,
  48.                                 tipY = e.pageY + o.mouseOffset.y,
  49.                                 tipWidth = st.outerWidth(true),
  50.                                 tipHeight = st.outerHeight(true);
  51.                         if(tipX + tipWidth > $(window).scrollLeft() + $(window).width()) tipX = e.pageX - tipWidth;
  52.                         if($(window).height()+$(window).scrollTop() < tipY + tipHeight) tipY = e.pageY - tipHeight;
  53.                         st.css({'left':tipX,'top':tipY}).fadeIn(o.fadeSpeed);
  54.                 });
  55.          });
  56.         }
  57.        
  58.         $.fn.simpletooltip.defaults = {
  59.                 html            : '',
  60.                 errorText       : '<b>Error:</b><br />No title attribute found<br />And no Html provide to the plugin.', //Leave it empty which will show nothing
  61.                 cornerRadius: 5,        
  62.                 cssClass        : '',
  63.                 opacity         : 0.9,
  64.                 fadeSpeed       : 'fast',
  65.                 mouseOffset: {
  66.                                                 x : 10,
  67.                                                 y : 10
  68.                                           },
  69.                 css                     : {
  70.                                                 'padding'       : 7,
  71.                                                 'background': '#F2F3F5',
  72.                                                 'border'        : '1px solid #A6A7AB',
  73.                                                 'width'         : '140px',
  74.                                                 'font-size'     : '12px'
  75.                                           }
  76.         };
  77.        
  78. })(jQuery);

Error fixed (in my last comment)

http://jquery.pastebin.com/f440ba663

Final one - Small bugs fixed :P

http://jquery.pastebin.com/f2c3b8c74

Aamir, it looks like the

Aamir, it looks like the newest version posted here:
http://jquery.pastebin.com/f2c3b8c74 gives an error in IE6, 7, and 8.

Any ideas??

thanks

thanks i got the tool tip. implemented in sharepoint custom list.

Post new comment

The content of this field is kept private and will not be shown publicly.
  • Allowed HTML tags: <a> <em> <strong> <cite> <code> <ul> <ol> <li> <dl> <dt> <dd>
  • Lines and paragraphs break automatically.
  • You can enable syntax highlighting of source code with the following tags: <code>, <blockcode>, <c>, <cpp>, <drupal5>, <drupal6>, <java>, <javascript>, <php>, <python>, <ruby>. Beside the tag style "<foo>" it is also possible to use "[foo]". PHP source code can also be enclosed in <?php ... ?> or <% ... %>.

More information about formatting options

CAPTCHA
This question is for testing whether you are a human visitor and to prevent automated spam submissions.
Image CAPTCHA
Enter the characters (without spaces) shown in the image.