How to create a tooltips with jQuery

Here’s a simple idea to create a tooltips message with jQuery.

Idea…

  1. Identify the “target” that need to show the tooltips message.
  2. Create a tooltips message and CSS style for it.
  3. Three functions, – showTooltips, hideTooltips, changeTooltipsPosition.
  4. While mouseenter the “target“, use showTooltips to show the tooltips message and initial the position with changeTooltipsPosition.
  5. While mousemove around the “target“, keep change the tooltips message position with changeTooltipsPosition.
  6. While mouseleave the “target”, use hideTooltips to hide the tooltips message.
  7. Use jQuery to do it :)

1. Target

The “hint” and “username label” are the target to show the tooltips message.

<label id="username">Username : </label><input type="text" / size="50"> 
<span id="hint">hint (mouseover me)</span>

2. Tooltips CSS

Create a CSS style for tooltips message.

.tooltip{
	margin:8px;
	padding:8px;
	border:1px solid blue;
	background-color:yellow;
	position: absolute;
	z-index: 2;
}

3. Show Tooltips

Append the tooltips message to the “body” tag, and initial the tooltips message position.

var showTooltip = function(event) {
   $('div.tooltip').remove();
   $('<div class="tooltip">I\' am tooltips! tooltips! tooltips! :)</div>')
     .appendTo('body');
   changeTooltipPosition(event);
};

5. Change Tooltips

Change the tooltips message position.

var changeTooltipPosition = function(event) {
	var tooltipX = event.pageX - 8;
	var tooltipY = event.pageY + 8;
	$('div.tooltip').css({top: tooltipY, left: tooltipX});
};

6. Hide Tooltips

Hide the tooltips message.

var hideTooltip = function() {
	$('div.tooltip').remove();
};

7. Bind It

Bind the mouse events to the target.

$("span#hint,label#username'").bind({
	mousemove : changeTooltipPosition,
	mouseenter : showTooltip,
	mouseleave: hideTooltip
});

Try it yourself

In this example, mouseover the hint or label to show the tooltips effect.

<html>
<head>
 
<script type="text/javascript" src="jquery-1.4.2.min.js"></script>
 
<style type="text/css">
	#hint{
		cursor:pointer;
	}
	.tooltip{
		margin:8px;
		padding:8px;
		border:1px solid blue;
		background-color:yellow;
		position: absolute;
		z-index: 2;
	}
</style>
 
</head>
 
<body>
 
<h1>jQuery tooltips example</h1>
 
<label id="username">Username : </label><input type="text" / size="50"> 
<span id="hint">hint (mouseover me)</span>
 
<script type="text/javascript">
 
$(document).ready(function() {
 
	var changeTooltipPosition = function(event) {
	  var tooltipX = event.pageX - 8;
	  var tooltipY = event.pageY + 8;
	  $('div.tooltip').css({top: tooltipY, left: tooltipX});
	};
 
	var showTooltip = function(event) {
	  $('div.tooltip').remove();
	  $('<div class="tooltip">I\' am tooltips! tooltips! tooltips! :)</div>')
            .appendTo('body');
	  changeTooltipPosition(event);
	};
 
	var hideTooltip = function() {
	   $('div.tooltip').remove();
	};
 
	$("span#hint,label#username'").bind({
	   mousemove : changeTooltipPosition,
	   mouseenter : showTooltip,
	   mouseleave: hideTooltip
	});
});
 
</script>
 
</body>
</html>
Tags :

About the Author

mkyong
Founder of Mkyong.com and HostingCompass.com, love Java and open source stuff. Follow him on Twitter, or befriend him on Facebook or Google Plus. If you like my tutorials, consider make a donation to these charities.

Comments

  • Pingback: HD Coloring Pages()

  • Pingback: electricians license()

  • Pingback: check this out()

  • Pingback: house blue()

  • Pingback: zak?ad szklarski piotrk√≥w trybunalski()

  • Pingback: water ionizer()

  • Pingback: i need plumber()

  • Pingback: i & s locksmiths cumnock()

  • Pingback: check that()

  • Pingback: discover more()

  • Pingback: pay per day loan plans()

  • Pingback: bottled alkaline water()

  • Pingback: car parking()

  • Pingback: alkaline water machine()

  • Pingback: car parking()

  • Pingback: 3gp mobile porn()

  • Pingback: laan penge her og nu()

  • Pingback: TV options for restaurants()

  • Pingback: get satellite tv()

  • Pingback: alkaline()

  • Pingback: alkaline water()

  • Pingback: watch free movies online()

  • Pingback: stream movies()

  • Pingback: tv online, online tv()

  • Pingback: How to loose weight()

  • Pingback: Blue Coaster33()

  • http://www.across.ph Kuiamenh Martin

    Nice article. This is what i’m looking for.
    Thanks sir mkyong :)

  • Rahul S

    Thanks man.. It was cool..
    Its really good to have for such customized tooltip div.

  • Hernan

    Hi,

    For tooltip, I have a scenario werein I have two images with tooltip with different message. As I testing it, the message set on the first tooltip is displaying on the second tooltip. I set the message differently though I used the same tooltip class in DIV. Can you advice on how I can do this? BTW, my scenario is, aside from two tooltip with different message, each toolip message has an url/link on it.

    Hoping to receieve a response as this is currently UAT issue in my side. Thanks

  • servane

    Hi, it’s very usefull but I’d like to know how to make a dynamic text in the tooltip.

    Thanks

  • Khalid

    thanks it’s nice

  • http://www.slideshare.net/dorothyclfm/the-company-store-coupon-coupons-available-now The Company coupon code

    Hi there just wanted to give you a quick heads up. The words in your article
    seem to be running off the screen in Opera. I’m not sure if this is a formatting issue or something to do with web browser compatibility but I thought I’d
    post to let you know. The design look great though!
    Hope you get the issue solved soon. Thanks

  • http://[email protected] SAGAR

    Please help me in learning javascript and jquery as well as ajax from basics to advance.as i have reviwed w3schhol.please tell me another link

  • Reddy

    How can I add a sticky tooltip using your code

  • http://zglen.com zack

    Works perfectly. Very instructive. Thank you!

  • Tushar Kadav

    Hi mkyong,

    I like your blog its really useful and I have implemented,and its easy to understand.I like the way you are explaining.

    Thanks a lot…

  • sainul abid

    Very useful. Good work.

  • http://hochzeit-trauung.com Lisa @ Hochzeit & Trauung

    it works for me

    thank you

  • Chandra

    This ocde is working fine in IE8 but not working in firefox. I used 1.7.2.min.js instead of 1.4.2.min.js.
    Please help me in resolving this issue.

  • aymen

    thank you so muccchh u saved my day !!! nice article

  • aymen

    thank you soooo much it saved my day !!! nice article

  • Steve

    Thanks for the tipp – it worked but first I had to remove the ‘ symbol
    @ $(“span#hint,label#username'”).bind({

    now it works, thanks!

  • Sam

    This is really helpful information, i tried same thing as you have shown here. I am getting following exception. Can you help me ??

    Webpage error details

    Message: ‘guid’ is null or not an object
    Line: 19
    Char: 13206
    Code: 0
    URI: http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js

  • RockMetal

    I’m so grateful for your straightforward tooltip idea and demo. I’m adapting this to a current WordPress site but can not get it to work. It works great if I simply create an HTML page in Dreamweaver but when I insert this into WordPress it simply doesn’t work. Basically i’ve tried a few variations but got so frustrated I just took your code verbatim including the selectors and still won’t work.

    What i’m trying to accomplish is for the tooltip to display on any link with a class of ‘ext-link’. So, I set the .bind to $(‘a.ext-link’).bind({blahblah}. No good. Nothing displays. So, I created a span called ‘hint’ (like your example), no good. Won’t display. Basically nothing works. I even tried binding it to any hyperlink with no luck. Either i’m missing something or there’s possibly a conflict with a plugin. The rest of your code is identical to your example.

    I’ve tried deactivating a few plugins that i’ve known to cause conflicts but still nothing. Is there anything special I need to know to make this work in a WordPress environment? Thanks in advance!

    • http://www.mkyong.com mkyong

      Make sure jQuery is working in your WordPress – Just output a simple message via jQuery, see if it works?

      • RockMetal

        Hey, thanks for your response. I did run a test and JQuery is working. Basically, aside from the test, there’s a bunch of other JQuery stuff going on as well (lightbox, slider, etc.). That’s what’s baffling me. I can’t see any reason why this won’t fire in the blog. I’m using this code:

        $(document).ready(function() {

        var changeTooltipPosition = function(event) {

        var tooltipX = event.pageX – 8;

        var tooltipY = event.pageY + 8;

        $(‘div.tooltip’).css({top: tooltipY, left: tooltipX});

        };

        var showTooltip = function(event) {

        $(‘div.tooltip’).remove();

        $(‘Clicking this link will exit this site.’)

        .appendTo(‘body’);

        changeTooltipPosition(event);

        };

        var hideTooltip = function() {

        $(‘div.tooltip’).remove();

        };

        $(‘a[href*=http’).bind({

        mousemove : changeTooltipPosition,

        mouseenter : showTooltip,

        mouseleave: hideTooltip

        });

        });

        Here’s the url if you want to take a look at the source code: http://www.simcomedia.com/handbook/

        • http://www.mkyong.com mkyong

          Put this in a simple test html, to test if it works? Then comment line by line (other plugins or stuffs that you feel may be a stopper) in your production site to identify where it go wrong.

          • RockMetal

            I did do that already. I have the same code in an html file at http://www.simcomedia.com/tooltips-demo.html and it works perfectly. It may be that i’m just not inserting this into the proper location in WordPress? I’ve inserted it into the header.php just before the tag.

            Also, i’ve tried several selectors including any/all elements to trigger it, and even created a special paragraph and span elements trying to trigger it. But, no matter what I do in WordPress it doesn’t display the tooltips.

            I’m wondering If I need to make this into a plugin? I’ve had no problems in the past with integrating some jquery stuff before. Something is missing and I can’t point it out.

        • http://www.mkyong.com mkyong

          Visited your http://www.simcomedia.com/handbook/, the tooltips are working fine?

  • http://www.zamshed.info Zamshed Farhan

    I am not able to use this in a Struts application. Have any idea to resolve this issue.

    • http://www.mkyong.com mkyong

      Just a JavaScript, just out it, dun need special integration.

  • http://www.zamshed.info Zamshed Farhan

    Very basic, but very useful example.

  • Jason

    hello, i want to do tooltip click function,because i want to distinguish it click or not click , but when i finish ,i find the tooltip’s positon is not correct,i just modify
    $(“span#hint,label#username'”).bind({
    mousemove: changeTooltipPosition,
    mouseenter: showTooltip,
    mouseleave: hideTooltip
    }).click(function () {
    showTooltip.call(this, event);
    });

  • Robi

    var showTooltip = function(event) {
    $(‘div.tooltip’).remove();
    $(‘:)…I\’ am tooltips! toolI\’ am tooltips! tool’)
    .appendTo(‘body’);
    changeTooltipPosition(event);
    };

    ####
    Im hope, that this will be correct :|

  • Robi

    var showTooltip = function(event) {
    $(‘div.tooltip’).remove();
    $(‘:)…I\’ am tooltips! toolI\’ am tooltips! tool’)
    .appendTo(‘body’);
    changeTooltipPosition(event);
    };

  • Robi

    Hi i have problem.

    I meen is, possible use PHP inside JQ
    What I have to change, to make this script correct ?

    ##############################
    // $date[date] <– is form mysql
    // $user="$name $surname $date[date]";
    (…)
    var showTooltip = function(event) {
    $('div.tooltip').remove();
    $('
    …some text…
    ‘)
    .appendTo(‘body’);
    changeTooltipPosition(event);
    };
    (…)