I have a hash based url (e.g. www.dummy.com#/hello/welcome), I want to trigger javascript code when /welcome changes to /start (e.g. www.dummy.com#/hello/start).
Following is the code I've tried but isn't working.
window.addEventListener("hashchange",function() {
alert('The hash has changed!');
},false);
The hashchange event only happens when the hash changes, so if you just type the URL and hit enter nothing happens. Therefore you need to handle more cases: 1) the hash changes, 2) user types URL and 3) the history forward/back button is used to navigate to the page.
const eitherhashorload = e => {
let hash = location.hash.substring(1);
if(!hash){
location.hash = 'welcome';
return;
}
console.log(hash);
};
window.addEventListener("hashchange", eitherhashorload);
document.addEventListener('DOMContentLoaded', eitherhashorload);
<p><a href="#start">Start</a> - <a href="#end">End</a></p>