25

I tried to control back button, but I can’t. In here;

Take control of the hardware back button using jQuery Mobile

  event.keyCode == 27 // That’s for escape
  event.keyCode == 8 // That’s for backspace...it's also working on browser, but it doesn’t work on my tablet.

How can I do it?

Peter Mortensen
  • 30,030
  • 21
  • 100
  • 124
Serkan
  • 641
  • 3
  • 11
  • 19
  • [How to detect if the back button is pressed in mobile phone](https://stackoverflow.com/q/39087816/1066234) – Avatar Mar 16 '22 at 05:21

2 Answers2

56

Recommended method pagecontainerbeforechange: https://jqmtricks.wordpress.com/2014/12/01/detect-back-navigation/


You need to listen to the navigation event and state.direction.

$(window).on("navigate", function (event, data) {
  var direction = data.state.direction;
  if (direction == 'back') {
    // Do something
  }
  if (direction == 'forward') {
    // Do something else
  }
});

jQuery Mobile API: Navigation event

Demo

Peter Mortensen
  • 30,030
  • 21
  • 100
  • 124
Omar
  • 32,261
  • 9
  • 68
  • 109
3

You can do this without jQuery Mobile

window.addEventListener("hashchange", function(e) {
    if(e.oldURL.length > e.newURL.length)
        alert("back")
});
<a href="#p2">goto page 2</a> and then use browser's navigation.</div>

And also Demo in CodePen.

Peter Mortensen
  • 30,030
  • 21
  • 100
  • 124
Mahdi Bashirpour
  • 13,853
  • 11
  • 101
  • 132