How do I get the position of an element that uses the Transform CSS property?

Asked

Viewed 2,434 times

6

Imagine I have a popup that’s centered on transform:translateX(-50%) translateY(-50%) (if you have doubt about this solution, you can see more about it here, adapted of these answers).

So far so good, the element is centered correctly, but let’s say for some reason I need to figure out his exact position in document browser (to implement a drag'n-drop for example). I tried the properties offsetTop and offsetLeft but they return the position of the element without the Transforms, ie it is a position "fake".

My question is, is there any property that returns the values real of an element that is positioned using translate?

Follow an example for better understanding: FIDDLE.

2 answers

7


As commented, the properties offsetTop and offsetLeft do not return the exact position of the element when it uses the CSS property translate().

The only property I know that works with translate() is the getBoundingClientRect(), and the most interesting: It is ancient and totally cross-browser (works even on IE6).

Here is an example of implementation:

var el = document.getElementById('popup'),
    pos = el.getBoundingClientRect();

alert('Top: '+pos.top+'\nLeft: '+pos.left); // retorna a posição REAL do elemento

And an example: FIDDLE

-1

When you use Translate, the position of the element is centered.

That way you need to get the width of the element and split by two, so you have the position left;

To catch the top, just take the height element and split by two.

  • Please, the code in the answer. The way it is is not considered a very valid answer.

  • Welcome to Stack Overflow, Rafael! I suggest you explain your solution better (a working example would be great!) and that you do not share contact details in responses - oh, and that tour to get to know Sopt better! :)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.