Ika Ika - 4 days ago 5
HTML Question

When user presses the certain key, make it like he clicked the button

I'm writing calculator in JavaScript and I want users be able to hit key (ex:8) and make it like he clicked the button.

Here is part of my HTML code (JavaScript is done already):

<div class="row">
<button onclick="addNum(this)">7</button>
<button onclick="addNum(this)">8</button>
<button onclick="addNum(this)">9</button>
<button onclick="addOp(this)">×</button>
</div>


Maybe you can suggest some jQuery plugin (I have little knowledge of it).

Thanks

Answer

Add a separate window.onkeydown function to handle all the key events that happens. so that you can have the full control over the input. Please have a look at the Key code table for more key codes

window.onkeydown = function (e) {
    var code = e.keyCode ? e.keyCode : e.which;
    if (code => 96 && code <= 105) { //numbers
        addNum(this);
    } else if (code == 107) { //add
        addOp(this);
    } else if (code == 107) { //other keycodes
        // their codes
    }
};

Comments