If the hash is being updated dynamically through user interactions or timed events, you can utilize the window.onhashchange event to monitor these changes instead of using setTimeout to check the hash.
window.onhashchange = function(e) {
alert('Back button clicked');
}
This event will trigger whenever the hash is modified, whether by navigating through history or programmatically changing it. If you only want your code to run when navigating with history buttons, you can incorporate an if statement to control this behavior. Check out this example for reference:
Alternatively, you could structure your code to respond to hash changes and manually updating the hash in a way that ensures your code executes as intended.
Here's an example setup:
<a href='#1' class='nav'>1<a/>
<a href='#2' class='nav'>2<a/>
<a href='#3' class='nav'>3<a/>
And the corresponding JavaScript/jQuery:
/*$('.nav').click(function() { // Uncomment this block if not modifying hash in HTML
window.location.hash = '#' + $(this).html();
});*/
function getLocationHash() {
return window.location.hash.substring(1);
}
window.onhashchange = function(e) {
switch(getLocationHash()) {
case '1':
execute code block 1;
break;
case '2':
execute code block 2;
break;
case '3':
execute code block 3;
break;
default:
// Code to be executed for other cases
}
}
You can see a similar implementation on my website: