JQuery issue with distribution and Keydown

I got help earlier here with what turned out to be a distribution problem, but now I'm trying to use HTML5 input autofocus , and now my code breaks.

Here is the code I'm working with:

<script type="text/javascript"> var $j = jQuery.noConflict(); $j(':not(form)').keydown(function(event) { $j('form').keydown(function(event) { event.stopPropagation(); }); if(event.keyCode==82) { $j(document).trigger(location.href = '/?random') } }); </script> 

Basically, I have a keyboard setup. If you press R, this will result in a random page.

I tried to disable this functionality when the user entered text in the form / input field for obvious reasons. This code works, EXCEPT, when I try to use autofocus. If you start typing directly on the page, and the first letter you enter is R, it goes to a random page.

If another letter is first typed, then R is entered as a regular letter. I’m kind of new to this, so any help is greatly appreciated! Thanks.

EDIT: upon further testing, it seems that the problem may not be autofocus, but mainly because only when the first letter that typed the letter is R, it crashes.

+4
source share
2 answers

your selector with "not" was wrong.

 <script type="text/javascript"> $(document).ready(function(){ $('body').keydown(function(event) { if(event.keyCode==82) { $(document).trigger(location.href = '/?random') } }); $('input, textarea').keydown(function(){ event.stopPropagation(); }); }); </script> 
0
source

The point is that you add the keydown event to the form element every time keydown is called for any other element.

Try it. I changed JS a bit ...

http://jsfiddle.net/CAjNR/1/

Here is the code from the script:

HTML:

 <form> <input type="text" autofocus /> <input type="text" /> <input type="text" /> <input type="text" /> <textarea></textarea> <div id="results"> </div> </form> 

Js

 var $j = jQuery.noConflict(); $j(document).keydown(function(event) { var key = event.keyCode | event.which; if(key==82) { $j('#results').append($j('<div>pressed: r</div>')); } }); $j('input, textarea').keydown(function(event) { event.stopPropagation(); }); 
0
source

All Articles