Window: hashchange event
The hashchange event is fired when the fragment identifier of the URL has changed (the part of the URL beginning with and following the # symbol).
This event does not fire when the hash is modified using history.pushState() or history.replaceState().
Syntax
Use the event name in addEventListener():
addEventListener("hashchange", (event) => { })
Alternatively, assign to the event handler property of the interface:
onhashchange = (event) => { }
Event type
A HashChangeEvent. Inherits from Event.
Event handler aliases
In addition to the Window interface, the event handler property onhashchange is also available on the following targets:
Examples
You can use the hashchange event in an addEventListener method:
window.addEventListener("hashchange", () => {
console.log("The hash has changed!");
});
Or use the onhashchange event handler property (but note that this replaces other event listeners added using onhashchange, if any):
function locationHashChanged() {
if (location.hash === "#cool-feature") {
console.log("You're visiting a cool feature!");
}
}
window.onhashchange = locationHashChanged;
Specifications
Browser compatibility
See also
- popstate event
这篇文档对你有帮助吗?
谢谢你的反馈!