Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Positioning a tooltip relative to another div in JQuery

Tags:

jquery

css

Here's my tooltips markup and CSS:

<div class="tooltip">Click here to like it</div>

.tooltip {
    position: absolute;
    display: none;
    background: url('images/tooltip.gif') no-repeat;
    width: 100%;
    height: 40px;
    font-size: 0.8em;
    line-height: 40px;
    padding: 0px 0px 0px 8px;
}

Now, I have a div on my page called #button_container. I would like to place this .tooltip div 150px to the right of that div via JQuery. I understand I need to set this tooltips top and left attributes, but not sure how.

Idealy the tooltips top attribute should be the same as #button_container (although #button_container isn't positioned absolutely) and 150 less than #button_container's left attribute.

I don't really know where to get started on this so any help would be very much appreciated. Thanks.

like image 591
VIVA LA NWO Avatar asked Jun 08 '10 01:06

VIVA LA NWO


1 Answers

Firstly a piece of advice: don't roll your own on this. There are many excellent jQuery tooltip plugins. Just use one of them.

That aside, if you want to go down this route, there are a couple of ways of doing it. The CSS positioning route is to use relative+absolute positioning:

#button_container { position: relative; }
div.tooltip { position: absolute; top: 20px; right: 20px; }

This requires the tooltip to be inside the button container. It has the advantage that the tooltip will move with the rest of the page elements.

The more common solution is to use something like:

$("#button_container").hover(function(evt) {
  $("div.tooltip").css({top: evt.pageY + 10, left: evt.pageX + 10}).fadeIn();
}, function() {
  $("div.tooltip").fadeOut();
});

Basically you move the tooltip relative to the mouse while over the relevant region.

like image 110
cletus Avatar answered Nov 15 '22 15:11

cletus