Prevent BACKSPACE from navigating back with jQuery (Like Google's Homepage)
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.
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/