How can I control the back button event in jQuery Mobile?
Asked Answered
P

2

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?

Pharmaceutical answered 13/8, 2013 at 14:34 Comment(1)
I
57

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

Involution answered 13/8, 2013 at 15:36 Comment(4)
data.state.direction is undefined for me in Chrome (on desktop), but otherwise works great! ThanksVarrian
@JonathanBenn try this then jqmtricks.wordpress.com/2014/12/01/detect-back-navigationInvolution
@Involution would you say it is better to use pagecontainerbeforechange over navigate since it has a wider scope?Jambalaya
@Jambalaya Yes, much better.Involution
U
4

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.

Uniliteral answered 21/5, 2019 at 8:16 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.