MisterDave MisterDave - 5 months ago 8
jQuery Question

Recognizing keydown() in JavaScript with Arrow Keys

I am trying to use JavaScript (inside PHP) to recognize keyDown events - specifically the arrow keys. I have looked through various threads on here, as well as other sources but have not been able to find a solution. My code looks like:

echo '<script>
alert ("Hi");
$(document).keydown = (function(e) {

if (e.which == 37 || e.which == 38) {
alert("It works!");
}
if (e.which == 39 || e.which == 40) {
alert("It works, also!");
}
});
</script>';


The first alert is just there so I know it is even recognizing the script, which it is. However, when I press the arrow keys - nothing happens.

Answer

Use this instead:

echo '<script>
  alert ("Hi");
  $( document ).on( "keydown", function ( e ) {

    if ( e.which == 37 || e.which == 38 ) {
        alert( "It works!" );
    }
    if ( e.which == 39 || e.which == 40 ) {
        alert( "It works, also!" );
    }
} );
</script>';

the code which you used will just add a method on the object which is returned by jquery and is not actually adding the listener :)