Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

the hashchange event of jQuery doesn't work if I open a page with hash directly

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?

like image 300
daisy Avatar asked Dec 18 '13 07:12

daisy


1 Answers

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')
}
like image 162
Arun P Johny Avatar answered Oct 16 '22 07:10

Arun P Johny