4

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 Answers2

4

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/

Artem Arkhipov
  • 7,025
  • 5
  • 30
  • 52
  • I think that use if could be a good solution too http://jsbin.com/relumuzimu/edit?html,js,output – Blind Jul 11 '16 at 21:53
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

radiantstatic
  • 342
  • 4
  • 20