Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the pageX and pageY of an Element without using event

Is there anyway to the positioning of any element without using e.pageX and e.pageY.

Check this fiddle

The fiddle is actually a poor attempt at what im trying to ask, but i though a visual example would be better. What i want to know is, Is it possible to find the X and Y co-ordinates of any element on the DOM by referencing using

 document.getElementByID('elementID');

or maybe

document.getElementsByTagName('TagName');

EDIT: Although i have used Jquery in the FIDDLE, I would like a possible solution using only JavaScript.

like image 924
MarsOne Avatar asked Nov 15 '13 11:11

MarsOne


3 Answers

You can find almost all jquery stuff here: http://youmightnotneedjquery.com/

$(el).offset();

the same as:

var rect = el.getBoundingClientRect();

{
  top: rect.top + document.body.scrollTop,
  left: rect.left + document.body.scrollLeft
}
like image 131
rufreakde Avatar answered Nov 16 '22 20:11

rufreakde


<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script>
$("#something").click(function(e){
   var parentOffset = $(this).parent().offset(); 
   //or $(this).offset(); if you really just want the current element's offset
   var relX = e.pageX - parentOffset.left;
   var relY = e.pageY - parentOffset.top;
});
</script>
like image 40
Lauris Kuznecovs Avatar answered Nov 16 '22 18:11

Lauris Kuznecovs


You may use

document.getElementById("elementID").offsetTop;
document.getElementById("elementID").offsetLeft;

Refer to MDN. They return the offset from the parent element. If you need the offset of the element in respect to the whole body it may get more tricky, as you will have to sum the offsets of each element in the chain.
Respectively for .getElementsByTagName, as each object in the DOM has these attributes.

.getBoundingClientRect is also worth a look.

var clientRectangle = document.getElementById("elementID").getBoundingClientRect();
console.log(clientRectangle.top); //or left, right, bottom
like image 21
KeyNone Avatar answered Nov 16 '22 19:11

KeyNone