Mika Tähtinen


Monday 25.1.2010 11.47

Using JavaScript location.hash to scroll to the bottom of an element

The comments area in IRC-Galleria has the commenting form at the bottom and usually when we link the user to comments, we would like the comment form to be visible but this can’t be achieved with the normal #comments hash in the url since it positions to the top of the element.

Didn’t find a solution for this so I created one myself. With this we can link to the bottom of the comments element ie. /user/Bro#comments::after

hashScroll: function() {
    if (!location.hash || location.hash.indexOf('::') < 0) {
        // Nothing to do
        return;
    }

    var parts = location.hash.split('::', 2);

    if (!parts[0] || !parts[1]) {
        // Invalid hash
        return;
    }

    var element = $$(parts[0]).first();

    if (!element) {
        // No element found
        return;
    }

    switch (parts[1]) {
        case 'after':
            window.scrollTo(0, Math.max(0, 
                                 element.cumulativeOffset().top + element.getHeight() 
                                    - document.viewport.getHeight()));
            break;
    }
}
irc-galleriaduunigaltsudevjavascript