window.addEventListener("hashchange",myFunction);
console.log(window.onhashchange); //This one prints NULL
window.onhashchange = myFunction;
console.log(window.onhashchange); // This one working fine.
function myFunction() {
alert("The anchor part has changed!");
}
Why I am not able to attach event listener using the addEventListener
method ? But window.onhashchange
working fine
EDIT I am indeed using the 'hashchange' not 'onhashchange' it was a typo.
window.addEventListener("hashchange",myFunction);
console.log(window.onhashchange); //This one prints NULL
window.onhashchange = myFunction;
console.log(window.onhashchange); // This one working fine.
function myFunction() {
alert("The anchor part has changed!");
}
Why I am not able to attach event listener using the addEventListener
method ? But window.onhashchange
working fine
EDIT I am indeed using the 'hashchange' not 'onhashchange' it was a typo.
Share Improve this question edited Nov 10, 2016 at 1:39 javanoob asked Nov 10, 2016 at 1:33 javanoobjavanoob 6,42218 gold badges71 silver badges92 bronze badges 1-
The getter
window.onhashchange
is not set doesn't mean it is not working. – Derek 朕會功夫 Commented Nov 10, 2016 at 1:44
2 Answers
Reset to default 6There is no onhashchange
event. There is a hashchange
event:
window.addEventListener('hashchange', myFunction, false);
Likewise, there is no onclick
event, but there is a click
event:
element.addEventListener('click', someFunction, false);
testing on*
properties for bound events is not an appropriate way to verify that a callback is bound. For testing, you'll have to trigger the event in some manner and have a test within the callback:
window.onhashchange = function () {
console.log('onhashchange property works');
};
window.addEventListener('hashchange', function () {
console.log('addEventListener method works');
}, false);
<a href="#example">Click this to test</a>
Successfully bound callbacks will not be exposed via the property.
I had the same issue and hashchange but function does not fired...
OLD CODE
const router = ()=>{//load new data}
window.addEventListener('hashchange',router())
**This is load new data but page not reload and just how old data, it fixed when i change to **
window.addEventListener('hashchange', () => {
router()})
hope it will help thanks