Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to distinguish plus/equals and equals keys in javascript?

I want to use the plus and minus keys to trigger the zoom in and out functions in my web app. The following code works, mostly:

$(document).keydown(function(e) { // requires jQuery
    console.log(e.keyCode);
    if (e.keyCode === 189) { // minus
        zoom_out();
        return false;
    }
    if (e.keyCode === 187) { // plus
        zoom_in();
        return false;
    }
});

The key code 187 it returned when pressing the =/+ key as well as the keypad + key. This is fine, if odd, but 187 is also returned from the keypad = key, which I don't want to use for zooming. How can I distinguish the +/=, =, and + keys?

like image 848
Ryan Avatar asked Dec 19 '11 23:12

Ryan


1 Answers

Use the shiftKey property.

If e.shiftKey is true (you guessed it!) Shift is being held down and so e.keyCode === 187 && e.shiftKey means + was pressed.

like image 59
Ry- Avatar answered Oct 14 '22 07:10

Ry-