1

I'm trying to create an effect similar to a tooltip with jQuery.

I'm reusing the same <div> element (id="tooltip") to display the tooltip. Therefore, I need to constantly move this <div> element every time the user moves the cursor over an element which should display a tooltip. When I use the offset() property, it works fine the first time but then if I move the mouse repeatedly from one icon to the other, the tooltip starts to jump to different locations.

You can try it out here:

http://jsfiddle.net/ZbwjQ/2/

Try moving the mouse from one icon to the other repeatedly, you'll notice that the tooltip jumps around incorrectly. It should always appear immediately to the right of the icon which is hovered over.

Senseful
  • 86,719
  • 67
  • 308
  • 465

3 Answers3

3

There are several problems in your code.

Divs aren't self-closing tags:

<div />     <!-- Wrong -->
<div></div> <!-- Good -->

When you have empty divs, add the following declaration in your CSS to ensure they have a body:

div {
  content: "";
}

The jQuery offset() function seems buggy in your case, because of your hidden #tooltip. Prefer the following code to change its offset:

$('#tooltip').css({
  top: o.top,
  left: o.left
});

Additionally, the o's creation seems very useless. You just have to modify directly the offsetvariable:

var offset = $(this).offset();
offset.left += $(this).width();
$('#tooltip').css({
    top: offset.top,
    left: offset.left
});

Finally, try not to access several times to the same element with a selector. jQuery will have to find your element in the whole DOM tree everytime you call it.

var tooltip = $("#tooltip"); // Use it in mousenter/mouseleave => Avoids 2 useless selections

// In your mousenter function
var el = $(this); // Use "el" to get offset/width => 1 useless selection avoided

You can find a working jsfiddle here.

ldiqual
  • 15,015
  • 6
  • 52
  • 90
2

the Jquery function .offset() does not work well when the element is hidden. See the post : jquery: get the offset of hidden element

Community
  • 1
  • 1
jlguenego
  • 1,192
  • 15
  • 23
0

I am a few days into JQuery and javascript, and my home-made tooltip was jumping around occasionally to odd areas of the screen. Tracking the position variables in the debug position in Joomla, I couldn't see any problem there, the tooltip was being told to go to the correct spot. It just wouldn't obediently go there all of the time. I saw this post and it made good sense, so I created variables for selectors I was calling more than one time. Didn't even get as far as using css to set the position, so I am still using offset. Nevertheless the jumping problem completely cleared up, I can't make the tooltip positioning go haywire anymore at all. Wasted some time on this, as you would expect for someone new, but I will always be declaring variables now right at the start. Besides, that's how we did it in Delphi.

GAHiebert
  • 36
  • 1
  • 5