3

I want to create a button which will run a previously ran function. ie i click buttonA to run Function A then click button B to run functionB i want to have a button which allows the user to go back to functionA by clicking a back button.

i thought i could a global variable to hold previous statements but it would not work as every function ran would overwrite the stored statements. here is some psuodo code to kind of explain what i mean

var globalvar;
globalvar = functionA;
function B { run globalvar};
Darren Murtagh
  • 591
  • 2
  • 6
  • 28
  • Similar: [How to Detect Browser Back Button event - Cross Browser](http://stackoverflow.com/q/25806608/55075) at SO – kenorb May 06 '16 at 16:25

2 Answers2

12

Use hash hyperlinks and the hashchange event. In jQuery:

$(window).on('hashchange',function() {
    var hash = location.hash.substring(1); // strip the leading # symbol
    // now run code based on whatever the value of 'hash' is
});

HTML:

<a href="#hash1">function A</a>
<a href="#hash2">function B</a>

Now, whenever the user clicks the browser's "back" button (or an HTML button that triggers history.go(-1)), it will go back to whatever hash was previously selected and trigger the hashchange event again.

http://jsfiddle.net/mblase75/hL5FZ/

Warning: older browsers like IE7 may not support hashchange or history.go().

Community
  • 1
  • 1
Blazemonger
  • 90,923
  • 26
  • 142
  • 180
  • [Might find already existing history plugins in this question](http://stackoverflow.com/questions/116446/what-is-the-best-back-button-jquery-plugin). – kapa May 01 '12 at 14:44
  • 1
    @bažmegakapa Yep, although if older browser support isn't needed, those plugins are probably overkill. I might use [Modernizr](http://modernizr.com/) for support and work around it for those rare cases instead. – Blazemonger May 01 '12 at 14:45
  • Of course, just thought it's worth adding it as a comment. Sometimes you just don't want to reinvent the wheel :). Upvoted btw. – kapa May 01 '12 at 14:47
3

JQuery method, and apply the class back to the link, e.g.:

$(document).ready(function(){
  $('a.back').click(function(){
    parent.history.back();
    return false;
  });
});
kenorb
  • 155,785
  • 88
  • 678
  • 743
STEEL
  • 8,955
  • 9
  • 67
  • 89