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 accomplish this?
I keep running into this problem with users in my app. They don't have focus on any element and hit BACKSPACE which throws them out of the app.
Use the onkeydown event and preventDefault() method to Disable Backspace and Delete key in JavaScript. Backspace char code is 8 and deletes key char code is 46.
Use onkeydown property and block key of backspace “8” or key “Backspace” to prevent users from using the backspace key in a textbox using JavaScript.
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();
}
});
I really like Andrew Whitaker's answer. It will, however, still navigate back when focused on a readonly, radio, or checkbox input field and will not allow backspace on contentEditable elements so I have added a slight modification. Credit goes to Andrew Whitaker.
$(document).on("keydown", function (e) {
if (e.which === 8 && !$(e.target).is("input:not([readonly]):not([type=radio]):not([type=checkbox]), textarea, [contentEditable], [contentEditable=true]")) {
e.preventDefault();
}
});
At the moment it seems to be necessary to have every variation [contentEditable] that is in the HTML since [contentEditable] != [contentEditable=true].
The way Google does this is kinda cool. When you press backspace, they focus the text field, preventing the users to navigate back!
You can try the same:
<script src="http://code.jquery.com/jquery.min.js" type="text/javascript"></script>
<input id="target" type="text" />
<script type="text/javascript">
$(document).keydown(function(e) { if (e.keyCode == 8) $('#target').focus(); });
</script>
demo : http://jsfiddle.net/epinapala/TxG5p/
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();
}
}});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With