Search code examples
javascriptjquery-mobilejquerykeycode

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


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?


Solution

  • 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