How can I prevent the backspace key from navigating back?

How can I prevent the backspace key from navigating back?

On IE I can do this with the (terribly non-standard, but working) jQuery
if ($.browser.msie)
$(document).keydown(function(e) { if (e.keyCode == 8) window.event.keyCode = 0;});

But is it possible to do in a way which works on Firefox, or in a cross-browser way for a bonus?
For the record:
$(document).keydown(function(e) { if (e.keyCode == 8) e.stopPropagation(); });

does nothing.
$(document).keydown(function(e) { if (e.keyCode == 8) e.preventDefault(); });

solves the problem, but renders the backspace key unusable on the page, which is even worse than the original behaviour.
The reason I do this is that I’m not creating a simple web page but a large application. It is incredibly annoying to lose 10 minutes of work just because you pressed backspace in the wrong place. The ratio of preventing mistakes vs. annoying users should be way above 1000/1 by preventing the backspace key from navigating back.
EDIT2: I’m not trying to prevent history navigation, just accidents.
EDIT3: @brentonstrines comment (moved here since the question is so popular): This is a long-term ‘fix’, but you could throw your support behind the Chromium bug to change this behavior in webkit


Solution 1:

This code solves the problem, at least in IE and Firefox (haven’t tested any other, but I give it a reasonable chance of working if the problem even exists in other browsers).

// Prevent the backspace key from navigating back.
$(document).unbind('keydown').bind('keydown', function (event) {
    if (event.keyCode === 8) {
        var doPrevent = true;
        var types = ["text", "password", "file", "search", "email", "number", "date", "color", "datetime", "datetime-local", "month", "range", "search", "tel", "time", "url", "week"];
        var d = $(event.srcElement ||;
        var disabled = d.prop("readonly") || d.prop("disabled");
        if (!disabled) {
            if (d[0].isContentEditable) {
                doPrevent = false;
            } else if ("input")) {
                var type = d.attr("type");
                if (type) {
                    type = type.toLowerCase();
                if (types.indexOf(type) > -1) {
                    doPrevent = false;
            } else if ("textarea")) {
                doPrevent = false;
        if (doPrevent) {
            return false;

Solution 2:

This code works on all browsers and swallows the backspace key when not on a form element, or if the form element is disabled|readOnly. It is also efficient, which is important when it is executing on every key typed in.

     * this swallows backspace keys on any non-input element.
     * stops backspace -> back
    var rx = /INPUT|SELECT|TEXTAREA/i;

    $(document).bind("keydown keypress", function(e){
        if( e.which == 8 ){ // 8 == backspace
            if(!rx.test( || || ){

Solution 3:

The other answers here have established that this cannot be done without whitelisting elements in which Backspace is allowed. This solution is not ideal because the whitelist is not as straightforward as merely textareas and text/password inputs, but is repeatedly found to be incomplete and needing to be updated.

Related:  Javascript: Extend a Function

However, since the purpose of suppressing the backspace functionality is merely to prevent users from accidentally losing data, the beforeunload solution is a good one because the modal popup is surprising–modal popups are bad when they are triggered as part of a standard workflow, because the user gets used to dismissing them without reading them, and they are annoying. In this case, the modal popup would only appear as an alternative to a rare and surprising action, and is therefore acceptable.

The problem is that an onbeforeunload modal must not pop up whenever the user navigates away from the page (such as when clicking a link or submitting a form), and we don’t want to start whitelisting or blacklisting specific onbeforeunload conditions.

The ideal combination of tradeoffs for a generalized solution is as follows: keep track of whether backspace is pressed, and only pop up the onbeforeunload modal if it is. In other words:

function confirmBackspaceNavigations () {
    var backspaceIsPressed = false
        if (event.which == 8) {
            backspaceIsPressed = true
        if (event.which == 8) {
            backspaceIsPressed = false
    $(window).on('beforeunload', function(){
        if (backspaceIsPressed) {
            backspaceIsPressed = false
            return "Are you sure you want to leave this page?"
} // confirmBackspaceNavigations

This has been tested to work in IE7+, FireFox, Chrome, Safari, and Opera. Just drop this function into your global.js and call it from any page where you don’t want users to accidentally lose their data.

Related:  MAC addresses in JavaScript

Note that this will not trigger on hashchange events, however in that context you can use other techniques to keep users from accidentally losing their data.

Solution 4:

A more elegant/concise solution:

  var $target = $(||e.srcElement);
  if(e.keyCode == 8 && !$'input,[contenteditable="true"],textarea'))

Solution 5:

Modification of erikkallen’s Answer to address different input types

I’ve found that an enterprising user might press backspace on a checkbox or a radio button in a vain attempt to clear it and instead they would navigate backwards and lose all of their data.

This change should address that issue.

New Edit to address content editable divs

    //Prevents backspace except in the case of textareas and text inputs to prevent user navigation.
    $(document).keydown(function (e) {
        var preventKeyPress;
        if (e.keyCode == 8) {
            var d = e.srcElement ||;
            switch (d.tagName.toUpperCase()) {
                case 'TEXTAREA':
                    preventKeyPress = d.readOnly || d.disabled;
                case 'INPUT':
                    preventKeyPress = d.readOnly || d.disabled ||
                        (d.attributes["type"] && $.inArray(d.attributes["type"].value.toLowerCase(), ["radio", "checkbox", "submit", "button"]) >= 0);
                case 'DIV':
                    preventKeyPress = d.readOnly || d.disabled || !(d.attributes["contentEditable"] && d.attributes["contentEditable"].value == "true");
                    preventKeyPress = true;
            preventKeyPress = false;

        if (preventKeyPress)

To test make 2 files.

Related:  Rails upgrade to angular 2

starthere.htm – open this first so you have a place to go back to

<a href="./test.htm">Navigate to here to test</a>

test.htm – This will navigate backwards when backspace is pressed while the checkbox or submit has focus (achieved by tabbing). Replace with my code to fix.

<script src="" type="text/javascript"></script>
<script type="text/javascript">

    $(document).keydown(function(e) {
        var doPrevent;
        if (e.keyCode == 8) {
            var d = e.srcElement ||;
            if (d.tagName.toUpperCase() == 'INPUT' || d.tagName.toUpperCase() == 'TEXTAREA') {
                doPrevent = d.readOnly || d.disabled;
                doPrevent = true;
            doPrevent = false;

        if (doPrevent)
<input type="text" />
<input type="radio" />
<input type="checkbox" />
<input type="submit" />

Solution 6:

Based on the comments it appears you want to stop people losing information in forms, if they press backspace to delete but the field is not focused.

In which case, you want to look at the onunload event handler. Stack Overflow uses it – if you try to leave a page when you’ve started writing an answer, it pops up a warning.