Skip to content

Instantly share code, notes, and snippets.

@MaffooClock
Last active April 13, 2016 19:35
Show Gist options
  • Save MaffooClock/d0c8d3fa2ae833577e0a760920a2a047 to your computer and use it in GitHub Desktop.
Save MaffooClock/d0c8d3fa2ae833577e0a760920a2a047 to your computer and use it in GitHub Desktop.
Browsers using Backspace keypress to navigate Back is evil, especially for large forms. On a jQuery-enabled page, this will capture Backspace and discard it unless a form field is in focus.
$(function() {
var tagRegex = /INPUT|SELECT|TEXTAREA/i;
var typeRegex = /DATE|DATETIME|DATETIME-LOCAL|EMAIL|MONTH|NUMBER|RANGE|SEARCH|TEL|TEXT|TIME|URL|WEEK/i;
$(document).on('keydown keypress', function(e) {
if (e.keyCode == 8) // Backspace
{
if ( !tagRegex.test(e.target.tagName) || e.target.tagName.toLowerCase() == 'input' && !typeRegex.test(e.target.type) )
{
e.preventDefault();
console.info('Prevented backspace key from navigating back. Tag: ' + e.target.tagName.toLowerCase() + ', ID: ' + (e.target.id || '(none)') + ', Type: ' + (e.target.type || '(none)'));
}
}
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment