How intercept these two key: ":" and "."?

929 Views Asked by At

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

Is there a way to intercept these two keys with JavaScript, jQuery or other?

1

There are 1 best solutions below

2
On BEST ANSWER

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; 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!");
        }
    }
};