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
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/
I've tryed many of the code snippets on the internet without satisfyind result. The new browser versions of IE (IE11) and Crome broke my former solution, but here is what works for me with IE11 + Crome + Firefox. The code prevents backspace and the user doesn't lose anything of what he has keyed in in a text field:
window.addEventListener('keydown', function (e) {
if (e.keyIdentifier === 'U+0008' || e.keyIdentifier === 'Backspace' || e.keyCode === '8' || document.activeElement !== 'text') {
if (e.target === document.body) {
e.preventDefault();
}
}
}, true);
Handled readonly text boxes also
$(document).keydown(function (e) {
var activeInput = $(document.activeElement).is("input[type=text]:not([readonly]):focus, textarea:focus");
if (e.keyCode === 8 && !activeInput) {
return false;
};
});
For Internet Explorer , this worked for me :
window.addEventListener('keydown', function (e) {
if (e.keyCode === 8) {
if (e.target === document.body) {
e.preventDefault();
}
}
}, true);
This is old, but these answers will still allow you to backspace and navigate when focused on a radio button. You will want to filter the input type as well. Credit to all answers above for this:
$(document).on("keydown", function (e) {
if (e.which === 8 && !$(e.target).is("input[type='text']:not([readonly]), 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].