0

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?

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
xRobot
  • 25,579
  • 69
  • 184
  • 304

1 Answers1

3

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!");
        }
    }
};
Delan Azabani
  • 79,602
  • 28
  • 170
  • 210
Tim Down
  • 318,141
  • 75
  • 454
  • 536
  • 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 Sep 21 '10 at 12:31
  • 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 Sep 21 '10 at 12:45