Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript or Jquery: Getting key inputs without focus

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

like image 706
user3871 Avatar asked Nov 30 '22 05:11

user3871


2 Answers

$(document).ready(function() {
    $(document).keydown(function(e) {   
      e.preventDefault();  
      if (e.which == 13) {
          // Whatever...
      }
    });
}); 
like image 159
castillo.io Avatar answered Dec 04 '22 10:12

castillo.io


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

like image 21
Fabrício Matté Avatar answered Dec 04 '22 10:12

Fabrício Matté