Getting the Coordinates of an Element

(Greg) #1

var d = hypeDocument.getElementById("box");
var topPos = d.offsetTop;
var leftPos = d.offsetLeft;
// alert (topPos + " " + leftPos)
hypeDocument.getElementById('coordinates').innerHTML = leftPos +"px" + " (left)" + " by " + topPos +"px" + " (top)" ;

Used with “On Mouse Click” from the Action Inspector.

(Greg) #2

You can also use getBoundingClientRect() to get the coordinates from the browser window (as the parent). The above method using “offset” gets the coordinates from the Hype window (as the parent).

var square = document.getElementById('box');
var squareRect = square.getBoundingClientRect(); // parent is the browser window
alert("Top " + ( + "px\n" + "Right " + (squareRect.right) + "px\n" + 
"Bottom " + (squareRect.bottom) + "px\n" + "Left " + (squareRect.left) + "px\n");

Note: I used “\n” to create a new line to make it easier to read…

(Greg) #3

You can put offset to use to build a measuring tool.

var d = hypeDocument.getElementById("box");
var leftPos = d.offsetLeft;
hypeDocument.getElementById('coords').innerHTML = leftPos + " pixels";

In a new Hype doc insert a rectangle with an “id” named “box” and a text box with an “id” named “coords”. Use the Action Inspector to set the “On Drag” functions to “Control Element Position” and attach the javascript there too.


This topic is slightly old, but if you’re hoping to detect and act on element position, this is now a bit easier with the addition of Getter / Setter api functions in Hype 3.5:

hypeDocument.getElementProperty(element, propertyName)


hypeDocument.setElementProperty(element, propertyName, value, optionalDuration, optionalTimingFunctionName)