Javascript or jQuery: getting key inputs without focus

I am trying to check if a key is pressed without focusing on any field.

The goal is to allow users to press the left and right arrows to move to the next image. There is no need for them to click on any text field or anything else ... just press these keys to go to the next or last image.

how

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 that jquery always needs a “selector”, as if I need to bind it to a field or something like that.

 $('input[type=text]').on('keyup', function(e) { if (e.which == 39) { run some code } }); 

Any ideas?

EDIT:

I have this script in my body viewimage.php ... javascript still doesn't work when the page loads:

 <script type="text/javascript"> $(document).ready(function() { $(document).keydown(function (e) { if (e.which == 39) { alert("39"); } }); }); </script> 

thanks

+4
source share
6 answers
 $(document).ready(function() { $(document).keydown(function(e) { e.preventDefault(); if (e.which == 13) { // Whatever... } }); }); 
+6
source

Add a listener to the document.

 $(document).on("keyup", function (e) { console.log(e.keyCode); });​ 
+2
source

Use $(document).on() or $(window).on()

+2
source

Bind the keyboard (or press or down) to the body, document or window. Use any or all of them (belts + braces).

 $('body',document,window).on('keyup', function(e) { if (e.which == 13) { e.preventDefault(); console.log('enter'); } });​ 
+2
source

First, keystrokes are safer, I think. I heard that in some browsers firmware and key firmware are missing.

I got it back ... keydown is the safest.

The answer to your question is to link the document:

 $(document).on('keydown', function(){ ... }); 
+2
source

I am trying to check if a key is pressed without focusing on any field.

If by field you mean the input elements / textearea / select, all you have to do is attach the handler to the document and cancel the above handler if the purpose of the event is the input element:

 $(document).on('keyup', function(e) { if ($(e.target).is('input, textarea, select')) return; if (e.which == 39) { console.log('move foward'); } }); 

Fiddle

+2
source

Source: https://habr.com/ru/post/1439005/


All Articles