I placed a script tag at the end of a html page:
$(window).on ('hashchange', function (e) { alert (location.hash); });
It works if I click on buttons with hrefs like #a
, but If I open links like localhost/aaa#a
the alert function is not triggered.
So it looks like I have to detect the presence of a hash when the document is ready. But that looked wrong.
Is there a way to make it work in both situations?
You have to trigger the event manually on page load. The event will only get triggered when there is a direct action from the user. Since it is page load with no action from the user the on hashchange event will not get triggered.
$(window).on('hashchange', function (e) {
alert(location.hash);
}).trigger('hashchange');
If you want to fire the event only when there is a hash value then
$(window).on('hashchange', function (e) {
alert(location.hash);
});
if (window.location.hash) {
$(window).trigger('hashchange')
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With