Tuesday, June 24, 2008

Anchoring Bookmarklet

Occasionally we find ourselves loading pages with lots of images, and trying to get to a specific piece of the page. The browser will jump to the proper location, which promptly scrolls away while the images load. To solve that problem, I threw together a JavaScript bookmarklet that will snap your window back to the position of whatever element holds the anchor. Here is the code:

var getLocationAnchor = function(url) {
    var i = url.indexOf('#');
    var id = (i >= 0 ? url.substr(i+1) : '');
    return decodeURIComponent(id);
};

var getAnchorNode = function(doc, id) {
    var chkNode = doc.getElementById(id);
    if (chkNode) {
        return chkNode;
    }

    var nodeList = doc.getElementsByName(id);
    for (var i = 0; i < nodeList.length; i++) {
        chkNode = nodeList.item(i);
        if (chkNode.tagName.toLowerCase() == 'a') {
            return chkNode;
        }
    }

    if (nodeList.length) {
        return nodeList.item(0);
    }

    return null;
};

var id = getLocationAnchor(document.location.href);
var node = getAnchorNode(document, id);
if (node) {
    node.scrollIntoView(true);
}

And converted into bookmarklet form, it looks much uglier. So the simple way to do this: bookmark this link.

Posted by Paul at 4:53 PM Perma-link | 0 comments | Links to this post |

Comments (Add)