The hashchange jQuery event does not work if I open the hash page directly

I placed the script tag at the end of the html page:

$(window).on ('hashchange', function (e) { alert (location.hash); });

It works if I press buttons with hrefs like #a , but if I open links like localhost/aaa#a , the warning function does not start.

So, it looks like I should detect a hash when the document is ready. But it didn’t look like that.

Is there a way to make it work in both situations?

+7
javascript jquery html
source share
1 answer

You must fire the event manually when the page loads. The event is activated only with direct user action. Since this is a page load without any user action, the hashchange event does not fire.

 $(window).on('hashchange', function (e) { alert(location.hash); }).trigger('hashchange'); 

If you want to fire an event only when there is a hash value, then

 $(window).on('hashchange', function (e) { alert(location.hash); }); if (window.location.hash) { $(window).trigger('hashchange') } 
+23
source share

All Articles