Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Firefox keydown backspace issue

I'm building a terminal emulation and running into an issue with capturing backspace in Firefox. I'm able to nab the first backspace and remove the last character on the input at the prompt, but it won't persist and remove more than one character.

Actual website: http://term.qt.io/

Replication here: http://jsfiddle.net/BgtsE/1/

JavaScript code

function handleKeys(e){
    var evt = e || window.event;
    var key = evt.charCode || evt.keyCode;
    if(evt.type == "keydown")
    {
        curr_key = key;
        if(key == 8)
        {
            evt.preventDefault();
            if(0 < $('body').text().length)
                $('body').text($('body').text().slice(0,-1));
        }
    }
    else if(evt.type == "keypress")
    {
        if(97 <= key && key <= 122)
        {
            if(curr_key != key)
                $('body').append(String.fromCharCode(key));
        }
        else
            $('body').append(String.fromCharCode(key));
    }
}
$(function(){
    $('html').live({
        keydown:function(e){
            handleKeys(e);
        },
        keypress:function(e){
            handleKeys(e);
        }
    })
})​
like image 859
Zack Zatkin-Gold Avatar asked Jan 25 '26 09:01

Zack Zatkin-Gold


1 Answers

Try this: http://jsfiddle.net/NBZG8/1/

You'll need to handle backspace in both keydown and keypress to support Chrome and Firefox

function handleKeys(e){
    var evt = e || window.event;
    var key = evt.charCode || evt.keyCode;

    if (evt.type == "keydown") {
        curr_key = key;
        if(key == 8 && !$.browser.mozilla) {
            backspaceHandler(evt);
        }
    } else if (evt.type == "keypress") {
        if (key == 8) {
            backspaceHandler(evt);
        } else if (97 <= key && key <= 122) {
            if(curr_key != key) {
                $('body').append(String.fromCharCode(key));
            }
        } else {
            $('body').append(String.fromCharCode(key));
        }
    }
}

function backspaceHandler(evt) {
    evt.preventDefault();
    if(0 < $('body').text().length) {
        $('body').text($('body').text().slice(0,-1));
    }  
};

$(function(){
    $('html').live({
        keydown : handleKeys,
        keypress : handleKeys
    })
})​
like image 75
snjoetw Avatar answered Jan 27 '26 23:01

snjoetw



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!