So based on this question I asked, what’s the most reliable way of getting position of objects that’s crossbrowser? Thx
Share
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
In general, assuming you have an element named
elem, it’s actually quite easy to get the X and Y coordinates of the top-left corners of an element, assuming you want these in document coordinates. In all browsers this is returned by theelem.offsetLeftandelem.offsetTopproperties.The only trick you have to be aware of is that if
elemis absolutely positioned in another element, say adivwith a left / top margin of 20px, these properties will return 0, as it only takes into account the current element and not the entire chain of elements. Luckily we can use a “chain-traversal” function to capture all of the margins of elements associated with a given element, tally them up to get the correct document coordinates.As Sime Vidas mentioned, there is also JQuery’s
position()andoffset()properties, in this case you would want theoffset()properties.You can also use the
getBoundingClientRect()method, however this returns the coordinates of an element relative to itsoffsetParentand thus is not entirely reliable. Look at the following examples:Also I suggest you read this.