How to trigger an event when hash location changes

时间:2016-07-11 21:48:30

标签: javascript jquery fragment-identifier

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?

2 个答案:

答案 0 :(得分:2)

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/

答案 1 :(得分:0)

if ("onhashchange" in window) {
    alert("The browser supports the hashchange event!");
}

▲ For Support // ▼ implementation

function locationHashChanged() {
    if (location.hash === "#somecoolfeature") {
        somecoolfeature();
    }
}

window.onhashchange = locationHashChanged;

Source: https://developer.mozilla.org/en-US/docs/Web/API/WindowEventHandlers/onhashchange