Search code examples
javascriptjqueryeventsscrollanchor

prevent jumping to anchor on hashchange event


I'd like to prevent jumping to an anchor on a hashchange event. I could figure out how to disable this behaviour when clicking on a link. but unfortunately, the same code doesn't work for hashchange events. here is my code:

$('.parent').on('click', 'a', function(e) {
    e.preventDefault(); // this works perfectly fine
});

$(window).on('hashchange', function(e) {
    e.preventDefault(); // doesn't work
});

Solution

  • According to the documentation, the hashchange event is not cancellable, whereas a click event is.