Notice while on Google\'s homepage, with no focus on any element, pressing BACKSPACE will put the focus into the search toolbar instead of navigating back.
How can I
I would bind an event handler to keydown
and prevent the default action of that event if we're dealing with the backspace key outside of a textarea
or input
:
$(document).on("keydown", function (e) {
if (e.which === 8 && !$(e.target).is("input, textarea")) {
e.preventDefault();
}
});
Here is a simple solution tested on IE, Chrome and Firefox.
$(document).on("keydown", function (event) {
// Chrome & Firefox || Internet Explorer
if (document.activeElement === document.body || document.activeElement === document.body.parentElement) {
// SPACE (32) o BACKSPACE (8)
if (event.keyCode === 32 || event.keyCode === 8) {
event.preventDefault();
}
}});
To stop from navigating simply this code works!
$(document).on("keydown", function (event) {
if (event.keyCode === 8) {
event.preventDefault();
}
});
But that will even also happen for input fields type text/textarea. So to restrict it for those fields, you may use
$(document).on("keydown", function (event) {
if (event.which === 8 && !$(event.target).is("input, textarea")) {
event.preventDefault();
}
});
In my case where I had a text field for calendar and whenever I'd click on that calendar, Select date and press backspace it'd navigate back to previous page. To prevent it for that field only I simply used
$('#myField').on("keydown", function (event) {
if (event.keyCode === 8 || event.which === 8) {
event.preventDefault();
}
});
I thought to mention for some to help ;-)