Search code examples
javascriptjqueryhashchange

hashchange prevents scrolling to targeted div


I have an accordion element, and I need to have different panes expand on hashchange. The code I made, expands it but it doesn't scroll the the targeted div, and page never ends loading.

function hashChange() {
    if (window.location.hash === '#senior-backend') {
        $('#senior-backend, #backend-developer, #senior-frontend, #frontend, #dev-ops').hide(50);
        $('#senior-backend').show(50);
        $('#job-posts').removeClass().addClass('beige-bg');
        $('#job-posts-top').removeClass().addClass('beige-spikes');
    } 
}

window.onhashchange = hashChange;

Could you please point out what am I doing wrong.

Thanks


Solution

  • You need to scroll the site using animate once you detect a change in the hash, for example:

    var dest = $('#yourSelector').position();
    var dtop = dest.top;
    
    $('html, body').animate({
        scrollTop: dtop
    });
    

    Living demo: http://jsfiddle.net/LZbK8/