I’m using this
$(window).bind('hashchange', gotohash);
to add deep linking to my app.
My problem is that it also fires when I click an <a> with href=#whatever
and I only want to use it when the user uses the back and forward buttons of the browser or goes directly to a url with hash in it.
I’m thinking of hashChangeEnabled=true/false and then turn it off on every click
but is there an easier way to detect whether it’s caused by click or not?
What is the best practice?
My Solution
var disableHashChange = false;
$(window).bind('hashchange', function(){
if(!disableHashChange ){
gotohash();
}
disableHashChange = false;
});
$('.link').click(function(){
disableHashChange = true;
}
Answer by imsky
var lastLinkEvent;
$(window).bind('hashchange', function(){
if(lastLinkEvent != window.location.hash){
gotohash();
lastLinkEvent = "";
}
});
$('.link').click(function(){
lastLinkEvent = $(this).attr('href');;
}
Thanks
The hashchange event will fire when you change location, so if you don’t want it to fire when links are clicked, either change the link href attribute or add a click handler that uses
preventDefault.Edit: Given that you want your links to work, you should set up an application variable constrained only to link events, such as
lastLinkEventand set it to the hash contained within its URL. Then in your processing function, check iflastLinkEventis already the hash, and if it is, prevent execution.