user6459745
user6459745

Reputation:

How to detect if the back button is pressed in mobile phone

Please how can I detect if the back button is been pressed in a mobile phone as shown in the image belowenter image description here

I tried using the normal way its been done on desktop like this

$(document).keypress(function(e){
    if(e.keyCode == 8){
        alert();
    }
});

But it's not working on mobile phones. Please anyone with a better clue?

Upvotes: 12

Views: 14626

Answers (1)

Rachel Gallen
Rachel Gallen

Reputation: 28563

One option is to use jquery mobile.

Here is a code sample (of jquery mobile)

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

Another option would be to add a 'hardwareBackPress' event listener, as demonstrated in this react-native code sample

According to this source, to detect the 'back' key, KEYCODE_BACK = 4 on Android.

Alternatively, you could integrate mobile-detect.js

Hope this helps

Upvotes: 6

Related Questions