-1

Possible Duplicate:
Is there a way to catch the back button event in javascript?

How can I detect a back or forth button click?

e.g.

if(back_button_clicked)
{
    alert('back button was clicked');
}
else if(forward_button_clicked)
{
    alert('forwardbutton was clicked');
}

As I want to run some special functions when the user does this.

Community
  • 1
  • 1
Cameron
  • 27,963
  • 100
  • 281
  • 483
  • You have just asked the same question -> http://stackoverflow.com/questions/8080151/running-jquery-ajax-function-when-user-clicks-the-back-or-forward-buttons – Manse Nov 10 '11 at 14:58
  • Not the same question! The other is related to ajax! – Cameron Nov 10 '11 at 14:59

4 Answers4

2

You can't. Browser buttons like back and forward are not revealed to Javascript. You could use JQuery's unload() event to run code when the user leaves the page, that's about it.

Nate B
  • 6,338
  • 25
  • 23
0

Try this jQuery plugin -

http://tkyk.github.com/jquery-history-plugin/

rogerlsmith
  • 6,670
  • 2
  • 20
  • 25
  • I'm already using a history plugin! What I need to do is run some function when a user clicks one of those buttons. – Cameron Nov 10 '11 at 14:46
0

You can bind to the unload event of the window :

$(window).unload( function () { alert("Bye now!"); } );

jQuery Documentation

But this wont tell you the direction - is this important ?

Manse
  • 37,765
  • 10
  • 83
  • 108
0
window.onpopstate = function (evt) {
    if (event.state) {
        alert('back or forth clicked');
    }
}
Cameron
  • 27,963
  • 100
  • 281
  • 483
  • Only a handful of browsers support the History APIs (pushState, and onpopstate) – gen_Eric Nov 10 '11 at 15:41
  • This looks like you plagiarized [Andy's answer](http://stackoverflow.com/questions/8080151/running-jquery-ajax-function-when-user-clicks-the-back-or-forward-buttons/8080184#8080184) from your duplicate question. – Brock Adams Nov 11 '11 at 01:15
  • I would hardly call it plagarism! Rather showing the answer to the question and it wasn't a duplicate question rather an answer that solves both problems! – Cameron Nov 11 '11 at 11:47