Reputation: 697
Does anyone know how to disable the ability to use the "backspace" key on your keyboard to navigate to the previous page you were on?
Right now, I have an invoice type web application, that if the user(on a mac) hits backspace to remove an element within a form field, after reaching the end of the entered item, if they hit the backspace again, it moves to the prior browsed page, making them lose data with the application that was entered.
Upvotes: 0
Views: 5414
Reputation: 35341
The downside to @Sam's answer is that if you click on an HTML element, such as a table, the Backspace key still takes you back. It only works if you click in a "clear space" that does not have any HTML elements.
I tweaked Sam's answer and took code from this answer to create this solution. It does not cover all edge cases, but it was enough for my use case.
function disableBackspaceNavigation() {
window.onkeydown = function(e) {
if (e.keyCode == 8 && !isTextBox(e.target)) e.preventDefault();
}
}
function isTextBox(element) {
var tagName = element.tagName.toLowerCase();
if (tagName !== "input") return false;
var typeAttr = element.getAttribute('type').toLowerCase();
return typeAttr === 'text';
}
Upvotes: 2
Reputation: 3160
window.onkeydown = function(e) {
if (e.keyCode == 8 && e.target == document.body)
e.preventDefault();
}
Explanation: The backspace key has keycode 8. Calling "preventDefault" means that the event does not cause the default behaviour of pressing the backspace key (i.e. navigating back a page). This behaviour only happens if the target of the event is the document's body.
Edit: jsfiddle example
Upvotes: 7