Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

getting the X and Y coordinates for a div element

I've been trying to make a javascript to get a X and Y coordinates of a div element. After some trying around I have come up with some numbers but I'm not sure how to validate the exact location of them(the script returns the X as 168 and Y as 258) I'm running the script with a screen resolution of 1280 x 800. This is the script I use to get this result:

function get_x(div) {
    var getY;
    var element = document.getElementById("" + div).offsetHeight;
    var get_center_screen = screen.width / 2;

    document.getElementById("span_x").innerHTML = element;
    return getX;
}

function get_y(div) {
    var getY;
    var element = document.getElementById("" + div).offsetWidth;
    var get_center_screen = screen.height / 2;

    document.getElementById("span_y").innerHTML = element;
    return getY;
}​

Now the question is. Would it be reasonable to assume that these are accurate coordinates returned by the function or is there an easy to to just spawn a little something on that location to see what exactly it is?

And finally how would I go about making this div element move? I know I should use a mousedown event handler and a while to keep moving the element but yeah any tips/hints are greatly appreciated my biggest concern is to how to get that while loop running.

like image 996
Jeffrey Klinkhamer Avatar asked May 04 '12 08:05

Jeffrey Klinkhamer


People also ask

How do you find the coordinates of an element in HTML?

Element coordinates: getBoundingClientRect. The method elem. getBoundingClientRect() returns window coordinates for a minimal rectangle that encloses elem as an object of built-in DOMRect class.

How do you find the X and Y coordinates on a screen?

You can use pyautogui. mouseInfo() . MouseInfo is an application to display the XY position and RGB color information of the pixel currently under the mouse.

How do you find the coordinate of an element?

Use the Element. getBoundingClientRect() Function to Get the Position of an Element in JavaScript. The getBoundingClientRect() function produces a DOMRect object containing information about an element's size and position in the viewport.

How do you set X and Y coordinates in HTML?

To draw a straight line on a canvas, use the following methods: moveTo(x,y) - defines the starting point of the line. lineTo(x,y) - defines the ending point of the line.


1 Answers

By far, the easiest way to get the absolute screen position of an element is getBoundingClientRect.

var element = document.getElementById('some-id');
var position = element.getBoundingClientRect();
var x = position.left;
var y = position.top;
// Et voilà!

Keep in mind, though, that the coordinates don’t include the document scroll offset.

like image 119
katspaugh Avatar answered Sep 20 '22 11:09

katspaugh