How to use browser back-button functionality with JavaScript
by iampeterbanjo on February 28, 2010
Use jQuery BBQ plugin in combination with hash change plugin to listen for window has change events.
Let’s assume that you have a button with an ID of ‘button’. Let’s assume it does something useful like close a pop-up but it can do anything really.
e.g.
1: //listen for hash tag changes so we can remove the popup
2: $(window).bind('hashchange',
3: function(event){
4: //did we add or substract the hash?
5: var currentHash = window.location.hash;
6: currentHash = currentHash.slice(1);
7: if(window.console && debug){
8: console.log(['listings.js: hashchange event detected. currentHash is ', currentHash ].join(''));
9: }
10:
11: if(currentHash === 'close' || currentHash === ''){
12: //remove event listener to prevent premature trigger
13: $(window).unbind('hashchange');
14: if(window.console && debug){
15: console.log('listings.js: haschange event unbound ');
16: console.log(['listings.js: haschange event.trigger is ',event.target].join(''));
17: }
18:
19: $("#button").trigger('click');
20: } else {
21: if(window.console && debug){
22: console.log('hash is not empty. doing nothing.');
23: }
24: }
25: event.preventDefault();
26: }
27: );
What’s with the Array.join(‘’) method?
Well I learnt from Google that this method is faster than concatenating a string with ‘+’. I’m always learning new ways to write better code.
Leave your comment