Jquery () position doesn't work properly in safari and chrome

I saw this question once or twice earlier, but never with an answer that relates to my problem (as far as I know). I have a tooltip that appears when a link is clicked. I set the position of the tooltip based on the position of the link like this:

$('#tooltip').css('left', $(this).position().left); 

This works fine in FF, IE, etc., but in Chrome and Safari the tooltip is always about 60 pixels or so on to the left than I want. I really don't like writing custom browser code, so is there any reason that anyone knows this will happen? Thanks in advance.

UPDATE: I was able to fix this problem by removing the marker: 0 auto-style from the link. Soooo ... this has been fixed, but I still don't know WHY this is a problem in safari and chrome.

+4
source share
4 answers

According to stackoverflow ettiquette, everything is fine to answer that you have your own question, so ... I was able to fix this problem by removing the marker: 0 auto-style from the link. Soooo ... this has been fixed, but I still don't know WHY this is a problem in safari and chrome. But at least it's fixed.

+2
source

position () refers to the position relative to the containing DOM element, as opposed to the position on the screen. The difference is probably due to differences in how the hierarchy of elements is displayed in Webkit browsers, rather than an error in jQuery.

You will need to check the hierarchies of the elements to find out which DOM element is causing your problem, or if you want to put your tooltip on the position of the element within the window, use offset () .

+6
source

Instead of using position() , as in your example:

 var link = $('#mymenu a'); var tooltip = $('#mymenu #tooltip'); link.click(function(){ tooltip.css('left', $(this).position().left); }); 

you can use the subtraction of the offset() element with the offset() its parent (not necessarily the closest parent):

 var parent = $('#mymenu'); var link = $('#mymenu a'); var tooltip = $('#mymenu #tooltip'); link.click(function(){ parent.css('position', 'relative'); tooltip.css('left', $(this).offset().left - parent.offset().left); }); 

It returns the same value as position() , but works correctly in both FF and Chrome.

+3
source

It just had the same problem and removing margin: 0 auto; was not an option (and this is not a solution :). This worked for my needs, since webkit reports the value we are looking for as a left margin (assuming margin> 0, otherwise it reports position().left !):

 iPosLeft = oEl.position().left + parseInt(oEl.css('marginLeft')); 
0
source

Source: https://habr.com/ru/post/1344092/


All Articles