Skip to content

Instantly share code, notes, and snippets.

@fedecarg
Last active December 28, 2015 13:19
Show Gist options
  • Select an option

  • Save fedecarg/7506664 to your computer and use it in GitHub Desktop.

Select an option

Save fedecarg/7506664 to your computer and use it in GitHub Desktop.

Get the absolute position of every link in an html document using JavaScript:

/**
 * The HTML <area> coords attribute needs the position of the left, top, right, bottom corner 
 * of the rectangle. Element.getBoundingClientRect returns a text rectangle object that encloses 
 * a group of text rectangles.
 */
function getElementAbsolutePosition(element) {
    var pos = {};
    pos.left = 0;
    pos.top = 0;
    pos.right = 0;
    pos.bottom = 0;
    
    if (element !== null && element.getBoundingClientRect) {
        var box = element.getBoundingClientRect();
        var body = document.body;
        var docElem = document.documentElement;
        var scrollTop = window.pageYOffset || docElem.scrollTop || body.scrollTop;
        var scrollLeft = window.pageXOffset || docElem.scrollLeft || body.scrollLeft;
        var clientTop = docElem.clientTop || body.clientTop || 0;
        var clientLeft = docElem.clientLeft || body.clientLeft || 0;
        pos.left = Math.round(box.left + scrollLeft - clientLeft);
        pos.top = Math.round(box.top + scrollTop - clientTop);
        pos.right = element.offsetWidth + pos.left;
        pos.bottom = element.offsetHeight + pos.top;
    }
    return pos;
}

var links = document.getElementsByTagName("a");
for(var i in links) {
    var element = links[i];
    console.log(element.href);
    pos = getElementAbsolutePosition(element);
    
    // show rectangles
    var div = document.createElement("div");
    document.body.appendChild(div);
    div.style.display = "block"
    div.style.position = "absolute"
    div.style.top = pos.top + "px"; 
    div.style.left = pos.left + "px";
    div.style.width = element.offsetWidth + "px";
    div.style.height = element.offsetHeight + "px";
    div.style.background = "red";
    div.style.zIndex = 1000;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment