Skip to content

Instantly share code, notes, and snippets.

@danwakefield
Last active December 23, 2015 13:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save danwakefield/ca5fc9eb5dc45c176dff to your computer and use it in GitHub Desktop.
Save danwakefield/ca5fc9eb5dc45c176dff to your computer and use it in GitHub Desktop.
Prevent backspace page redirect with vanilla javascript
function preventBackspace() {
function matchesSelector_(el, selector) {
return (el.matches || el.msMatchesSelector).call(el, selector);
}
function prevent(e) {
if (e.which === 8) { // Backspace
if (!matchesSelector_(e.target, 'input:not([readonly]):not([type=radio]):not([type=checkbox]), textarea, [contentEditable], [contentEditable=true]')) {
e.preventDefault();
}
}
}
document.addEventListener('keydown', prevent);
document.addEventListener('keyup', prevent);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment