• Finding the X & Y coordinates of an element relative to the entire page using Javascript

    It’s really easy to get the position of an element relative to it’s parent element, but what if you wanted to get it’s position relative to the entire page (viewport)? There’s no javascript call to do this, but here is a function to get the elements x & y coordinates.

    If you use the prototype javascript framework there is a call built in! Handy…

    Here’s the code for Prototype users:

    var pos = $("elementID").viewportOffset();
    var x = pos[0];
    var y = pos[1];

    Nice and easy…

    For those of you who don’t use prototype, below is a function you can use to get the X & Y coordinates relative to the page (viewport).

    The Function:

    function viewportOffset(forElement) {
    	var valueT = 0, valueL = 0;<
    	var element = document.getElementById(forElement);
    	do {
    		valueT += element.offsetTop  || 0;
    		valueL += element.offsetLeft || 0;
    		if (element.offsetParent == document.body) break;
    	} while (element = element.offsetParent);
    	element = forElement;
    	do {
    		if (element.tagName == 'BODY') {
    			valueT -= element.scrollTop  || 0;
    			valueL -= element.scrollLeft || 0;
    		}
    	} while (element = element.parentNode);
    	return [valueL, valueT];
    }

    This is a modified function from the prototype framework.

    Calling The Function:

    var pos = viewportOffset("elementID");
    var x = pos[0];
    var y = pos[1];

    I tried several of the functions on various blogs etc none of them seemed to return anything but 0 in Safari. The above has been tested and works in the latest versions Safari, Firefox, IE and Opera.

    Enjoy!

    Tags: , , , ,

Leave a comment