JavaScript keyword listener is disabled when inside a text form

I have a keyboard assigned to the arrow keys to navigate the slide show. But I want to temporarily disable the key listener while the user enters text inside the input field. How can i do this? My current code is as follows:

//Listen to the keys function checkKey(e) { switch (e.keyCode) { case 37: changeImage('prev'); break; case 39: changeImage('next');; break; } } if (jQuery.browser.mozilla) { jQuery(document).keypress (checkKey); } else { jQuery(document).keydown (checkKey); } 

Thanks.

+4
source share
5 answers

Firstly, there is no need to check the browser. To test the arrow keys, simply use the keydown event for all keys.

Secondly, I suggest (as Sean Hogan did) by checking the purpose of the event before doing a slide show. The following will work on all major desktop browsers:

 document.body.onkeydown = function(evt) { evt = evt || window.event; var target = evt.target || evt.srcElement; var targetTagName = (target.nodeType == 1) ? target.nodeName.toUpperCase() : ""; if ( !/INPUT|SELECT|TEXTAREA/.test(targetTagName) ) { switch (evt.keyCode) { case 37: changeImage('prev'); break; case 39: changeImage('next'); break; } } } 
+2
source

A bit ugly, but should work:

 var moz = jQuery.browser.mozilla; if (moz) { jQuery(document).keypress(checkKey); } else { jQuery(document).keydown(checkKey); } jQuery("#myInput").focus(function() { if (moz) { jQuery(document).unbind("keypress"); } else { jQuery(document).unbind("keydown"); } }).blur(function() { if (moz) { jQuery(document).keypress(checkKey); } else { jQuery(document).keydown(checkKey); } }); 
+2
source

If the focus is on the input element, then this element will become the target for key events.

So you can just check on event.target.tagName.

eg.

 function checkKey(e) { switch (e.target.tagName) { case "INPUT": case "SELECT": case "TEXTAREA": return; } // rest of your handler goes here ... } 
+2
source

Add the onfocus and onblur event to the input field and set the value of the global variable. Check this global variable at the beginning of the checkKey event handler.

 <input type="textbox" onfocus="window.inTextBox = true;" onblur="window.inTextBox = false;" /> function checkKey(e) { if (!window.inTextBox) { ... } } 
+1
source

I really like the simplicity of Ilya Volodin's suggestion, but I would install an event handler in a script and not embed it in html:

  var textFocus = false; $("textbox").focus(function() { textFocus = true; }); $("textbox").blur(function() { textFocus = false; }); function navKeys() { if (textFocus) { return false; } else { ...... } } 

This would be even simpler if jquery had :focus as a selector.

  function navKeys() { if ($("textbox:focus") { return false; } else { ...... } } 

But this is only a hypothetical code at the moment.

0
source

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


All Articles