Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I position a tooltip relative to its trigger element in jQuery?

Tags:

jquery

I would like to display a JSON response (from an ajax call) in a tooltip. I would like to position the tooltip relative to its trigger element, an anchor, underneath it to its left. I will have many trigger elements on the same page. I thought of using something like this:

$.ajax({
    // Do stuff
    success: function(response) {
        $(this).after("<div class='tooltip'>" + response.message + "</div>");
    }
});

This code doesn't solve my problem. It inserts the tooltip in the target element's container. I need the tooltip to float and be independent from the target element, sort of like the tooltips StackOverFlow displays when you vote on a post.

Any ideas how to do this in jQuery?

like image 268
Mohamad Avatar asked Sep 05 '25 01:09

Mohamad


2 Answers

To make your tooltip independent of other elements, it should be a direct child of your <body> and with a high z-index CSS property.

If you try to drop the tooltip into the DOM anywhere else it could interfere with page layout.

Then just use absolute positioning based on the coordinates of the trigger element.

.tooltip {
    z-index: 10000;
    position: absolute;
}

var offset = $(trigger).offset();
offset.top += $(trigger).height();
$(tooltip).offset(offset);
like image 73
Alnitak Avatar answered Sep 07 '25 14:09

Alnitak


You can use jquery ui position() to place your tooltip with response relatively to particular element.

like image 21
Litek Avatar answered Sep 07 '25 14:09

Litek