You've tagged your question jquery
, so I'll assume you are actually using it.
There are several issues there:
keypress
is only triggered for printable characters. For arrow keys, you want keydown
(usually) or keyup
(rarely).
jQuery instances don't have an addEventListener
method. You want on
. (Or you could use the event-specific alias for the event you want to use.)
There is no third argument to the jQuery on
method.
jQuery handles the issue of the event argument being passed by some handler mechanisms and not by others for you. It always gives you the argument.
Some browsers use keyCode
, others use which
. jQuery standardizes it for you as which
.
So:
$('#divID').on('keydown', function(e) {
if (e.which == 40) {
//do something when the down arrow key is pressed.
}
});
More: on
, the event object
For the div
to receive the keypress, on at least some browsers, it will need to either be or have interactive content (for instance, it would need to have an input
in it, or be contenteditable
, or similar).
Live Example with a contenteditable
div
$('#divID').on('keydown', function(e) {
if (e.which == 40) {
//do something when the down arrow key is pressed.
$("<p>").text("down arrow").appendTo(document.body);
return false;
}
});
<div id="divID" contenteditable>Click here to ensure the div has focus, then press the down arrow</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
Alternately, capture the keydown event on document.body
(or document
):
Live Example with document.body
:
$(document.body).on('keydown', function(e) {
if (e.which == 40) {
//do something when the down arrow key is pressed.
$("<p>").text("down arrow").appendTo(document.body);
return false;
}
});
<div id="divID">Click here to ensure the document has focus, then press the down arrow</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>