Reputation:
Please how can I detect if the back button is been pressed in a mobile phone as shown in the image below
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
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