Search code examples
javascriptjqueryfragment-identifier

How to trigger an event when hash location changes


I'm trying to trigger an event when the hash changes inside my url using the method onhashchange. I'm calling it, but it doesn't ever seem to get executed.

I've tried the following.

$(function () {
    window.addEventListener("onhashchange", function () {
        alert("Here");
    });

    window.onhashchange = function () {
        alert("Changed");
    }
)};

is there any reason why these functions aren't being called?


Solution

  • You should write 'hashchange' instead of 'onhashchange' in your first example.

    This code works fine for me, at least in Chrome:

    window.addEventListener('hashchange', function(e){
        console.log('changed');
    })
    

    Here is short code-snippet: https://jsfiddle.net/bm8jjwmq/