What am I doing wrong here? The idea is that I can separate the arrow key presses from anything else, but the every key press is firing the alert 'you pressed an arrow key'. Any help would be great!
jsFiddle here or:
<input id='foo'>
<script>
$('#foo').keyup(function (e) {
var key = e.keyCode;
if ($.inArray(key, [37, 38, 39, 40])) {
alert('you pressed an arrow key');
} else {
alert("you didn't press an arrow key");
}
});
</script>
You have to check if it returns an index > -1. The index is -1 if there is no occurrence of the key in the array:
if ($.inArray(key, [37, 38, 39, 40]) > -1)
The jQuery inArray function returns the index of the value. For the left arrow key (37) it is returning 0 and it is being interpreted as false. You should change your code to be >=0
if ($.inArray(key, [37, 38, 39, 40]) > -1)
inArray
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With