Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a tooltip with jquery without a plugin?

Tags:

jquery

css

I have used a few different tooltip plugins over the years, but I think its become time to write my own. Simply, I'm not looking for a plugin which has all the options, as I know how I want every tooltip that pops up to look and behave. Most plugins have a range of animation and positions available and I think thats excessive for the lightweight one I'm wanting to create, with your help of course :)

Basically, using the title attribute of the hover, I want a tooltip to appear directly above and centered to the element being hovered.

I know how to populate the div that will be shown, but what I'm trying to work out, is how to tell that div to position itself directly above the element.

ideally this is done with minimal code. My logic says something like this (pseudo code):

<html>
<head>

<style type="text/css">

    #myToolTip { display: none; }

</style>

<script type="text/javascript">

$(document).ready(function() {

    $('.hoverAble').hover(function(){

        var tip = $(this).attr('title');

        $('#myToolTip').html(tip).fadeIn();

    }, function() {

        $('#myToolTip').fadeOut();

    }

});
</script>
</head>
<body>

<div id="myToolTip"></div>

<div class="hoverAble" title="I am good at code"></div>

</body>
</html>

of course the above code is just going to fill the tooltip and not be positioned relative to the hovered element. Thats where my understanding falls short. Can you help?

Edit: Just for clarification, i'm not wanting the tooltip to move with the mouse.

like image 885
willdanceforfun Avatar asked Aug 10 '09 12:08

willdanceforfun


1 Answers

Take a look at the various CSS functions in jQuery, mostly offset() and maybe height().

// pseudocode, assuming #tooltip has position: absolute
// do something similar with the left offset as well
$('#tooltip').css({ top : $('#link').offset().top + 10 + 'px' });

This would place the tooltip statically over, or close to, the link, which I think is what you're looking for. If you want the tooltip to move with the mouse, you'll need to dynamically update the position in a mousemove event.

like image 145
deceze Avatar answered Nov 03 '22 14:11

deceze