Capture the enter key cross-browser, my solution isn't working

linus72982 picture linus72982 · May 1, 2011 · Viewed 8.9k times · Source

I have what I thought was a cross-browser solution to capturing the enter key in a chat script I'm making, here it is:

    nn=(document.layers)?true:false;
ie=(document.all)?true:false;
function keyDown(e) {
    var evt=(e)?e:(window.event)?window.event:null;
    if(evt){
        var key=(evt.charCode)?evt.charCode: ((evt.keyCode)?evt.keyCode:((evt.which)?evt.which:0));
        if(key=="13") document.getElementById('chatEnter').submit();
        }
    }
document.onkeydown=keyDown;
if(nn) document.captureEvents(Event.KEYDOWN);

I got this from someone else so perhaps it's outdated? Anyway, the form id attribute is chatEnter as you can see. I've also tried using document.forms[0].submit and that didn't work either. It works just fine in FF but no luck in IE8 64 bit (those are the only two I've tested on thus far.) What am I doing wrong here? Thanks for any help.

Answer

neebz picture neebz · May 1, 2011

try using >

$(document).keypress(function(e) {
    if (e.which == "13") { 
        //enter pressed 
    }       
});

ofcourse you would require jQuery for it. There can't be a better cross-browser solution than to use a tested and widely used cross browser framework.