How can I determine if a user presses the keyboard's backspace key?

Issue

How can I determine if a user clicks on the keyboard’s backspace key as this will cancel the current working web form?

Solution

You can use the following jQuery code to capture the event:

//--- fix to avoid some situations (not all) backspace loading the previous page in IE and/or Firefox //-- if the focus is on the page and not on any control, in IE the page will still reload
$(function(){
 var BACKSPACE_KEY = 8;
 // Mozilla catch event as e.target while IS catch event.srcElement
 $(document).keypress(function(e){
 skipBackspaceKey = false;
 // detect if the browser is Mozilla // If so, check if backspace or other keys (experiemental) is pressed when not on textbox fields // if so, ignore the key press
  if ($.browser.mozilla)
  {
 if ( (e.altKey) || ((e.keyCode == BACKSPACE_KEY) 
 (e.target.type != "text" 
 e.target.type != "textarea" 
 e.target.type != "password")) ||
 ((e.ctrlKey) ((e.keyCode == 78) ||
 (e.keyCode == 82)) ) ||(e.keyCode == 116) )
 {
 e.keyCode = 0;
 e.returnValue = false;
 skipBackspaceKey = true;
 }
 }
  return (!skipBackspaceKey);
 });

 $(document).keydown(function(event){
 skipBackspaceKey = false;

 // detect if the browser is MS IE.
 // If so, check if backspace or other keys (experimental) is pressed when no on textbox fields
 // if so, ignore the key press
  if ($.browser.msie)
  {
 if ( (event.altKey) || ((event.keyCode == BACKSPACE_KEY) 
 (event.srcElement.type != "text" 
 event.srcElement.type != "textarea" 
 event.srcElement.type != "password")) ||
 ((event.ctrlKey) ((event.keyCode == 78) ||
 (event.keyCode == 82)) ) ||(event.keyCode == 116) )
 {
 event.keyCode = 0;
 event.returnValue = false;
 skipBackspaceKey = true;
 }
 }
  return (!skipBackspaceKey);
 });

});

Note: This jQuery script is experimental and we are providing the code as is. We cannot guarantee its functionality depending on the actual web form, and the user’s browser type and version.