I'm trying to check if a key is pressed without focus on any sort of field.
The goal is to allow users to press left and right arrow to get to the next image. There is no need for them to click into any text field or anything... just simply press those keys to scroll to the next or last image.
Like:
function keyEvent(e) {
if(e.keyCode == 39) {
run some code to get next image
}
else if (e.keyCode == 37) {
run some code to get last image
}
}
It seems like jquery always needs a "selector", as though I need to bind it to a field or something.
$('input[type=text]').on('keyup', function(e) {
if (e.which == 39) {
run some code
} });
Any ideas?
EDIT:
I have this script in my viewimage.php file body... the javascript still isn't running on page load:
<script type="text/javascript">
$(document).ready(function() {
$(document).keydown(function (e) {
if (e.which == 39) {
alert("39");
}
});
});
</script>
Thank you
$(document).ready(function() {
$(document).keydown(function(e) {
e.preventDefault();
if (e.which == 13) {
// Whatever...
}
});
});
I'm trying to check if a key is pressed without focus on any sort of field.
If by field
you mean input/textearea/select elements, all you have to do is attach a handler to the document and cancel the aforementioned handler if the event target is an input element:
$(document).on('keyup', function(e) {
if ($(e.target).is('input, textarea, select')) return;
if (e.which == 39) {
console.log('move foward');
}
});
Fiddle
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