In my web wordgame Qindar.net I wanted to allow the players to use the keyboard to place words on the game board. This included use of the arrow keys to navigate, and the backspace key to ‘delete’ wrongly placed letters.
I did find a way of masking the backspace key that works in all the browsers I have tested it against. The trick for most browsers is to override the onkeydown event, check for event number “8” and return ‘false’ from that event. This signals to the browser not to process that key.
As often happens one particular browser is troublesome, in this case it was Opera, that needed “onkeypress” overriding rather than “onkeydown”.
Yesterday I had an email query recently asking how this was done so I’ve detailed it here.
There’s a demo here. Select ‘View Source’ in your browser to see how it’s done.
- <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
- <html xmlns="http://www.w3.org/1999/xhtml" >
- <title>Backspace Browser Trap Demo</title>
- <p>Try pressing backspace on this page.</p>
- <p>Note you can still go 'back' with Alt + Left</p>
- <p id="keypressed"></p>
- // function to possibly override keypress
- trapfunction = function(event)
- var keynum;
- if (window.event) // eg. IE
- keynum = window.event.keyCode;
- else if (event.which) // eg. Firefox
- keynum = event.which;
- if (keynum == 8) // backspace has code 8
- document.getElementById("keypressed").innerHTML = "Backspace pressed";
- // display a message
- return false;
- // nullifies the backspace
- return true;
- document.onkeyup = function(event)
- document.getElementById("keypressed").innerHTML = ""; // clear the message
- return true;
- document.onkeydown = trapfunction; // IE, Firefox, Safari
- document.onkeypress = trapfunction; // only Opera needs the backspace nullifying in onkeypress