views:

106

answers:

1

I need to do something when a user push "." and something else when an user push ":"

Is there a way to intercept these 2 key with javascript, jQuery or other ?

+2  A: 

Assuming you want to intercept these keys on the whole document:

document.onkeypress = function(evt) {
    evt = evt || window.event;
    var charCode = (typeof evt.which == "undefined") ? evt.keyCode : evt.which;
    if (charCode) {
        var charStr = String.fromCharCode(charCode);
        if (charStr == ":") {
            alert("Colon!");
        } else if (charStr == ".") {
            alert("Full stop!");
        }
    }
};

Marcel Korpel rightly points out in the comments that it's more efficient not to use the String.fromCharCode() call, so here's a version without:

document.onkeypress = function(evt) {
    evt = evt || window.event;
    var charCode = (typeof evt.which == "undefined") ? evt.keyCode : evt.which;
    if (charCode) {
        if (charCode == 58) {
            alert("Colon!");
        } else if (charCode == 46) {
            alert("Full stop!");
        }
    }
};
Tim Down
@Tim: I agree, only using `String.fromCharCode` seems a bit overkill to me: if I'm not mistaken you can simply test `charCode` being either 46 (`.`) or 58 (`:`).
Marcel Korpel
Marcel: yes, I agree, and I probably would do that in production code but thought it was clearer what the code is doing with the `String.fromCharCode`. I'll add another version to my answer.
Tim Down