keithamus / jwerty

⌨ Awesome handling of keyboard events
http://keithamus.github.io/jwerty
Other
1.21k stars 109 forks source link

Disabling jwerty from focused textarea, input, select, etc #39

Closed jayroh closed 11 years ago

jayroh commented 11 years ago

Hello!

Looking through your extended readme it looks like this should be possible but I'm having a hard time tracking down what I might be doing wrong

<script type='text/javascript' src='http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js'></script>
<script type='text/javascript' src='../lib/jwerty.js'></script>

<input id='q' name='q' />

<script>
    focus_input = function(){
      jQuery('#q').focus();
      return true;
    }

    alert_j = function(){
      alert('j');
      return true;
    }

    jwerty.key('i', focus_input);
    jwerty.key('j', alert_j);
    jwerty.key('j', false, '#q');
</script>

In this case I bind "i" to focus on that form input and "j" to alert the letter "j".

I expect that when the element is focused on #q, however, that the "j" key event will not fire as specified in the last line within the script tag.

Desired effect:

Current (undesired) effect:

Looking forward to your thoughts!

Using the latest jwerty and jQuery 1.10.2

keithamus commented 11 years ago

@jayroh You're very close with the code you have, but the jwerty.key('<key>', false) shortcut is for preventing the default behaviour of the action, and does not stopPropagation, which is what you want. (See https://github.com/keithamus/jwerty/blob/master/jwerty.js#L384)

So instead of having jwerty.key('j', false, '#q');, try jwerty.key('j', function (e) { e.stopPropagation() }, '#q');.

As an aside, you should probably also return false in focus_input to prevent the "i" character from appearing in the input when it is focussed.

See this jsfiddle for the full, working code

klash75 commented 10 years ago

hello, can we use this plugin for ajax enabled web apps. I mean using ajax, different page gets loaded on same page. so can we use this plugin to add key event to trigger event on different loaded pages. Thanks in advance

keithamus commented 10 years ago

Sure, you want to use event delegation (with jQuery) to do such a thing. The delegate element will need to be something that doesn't change, e.g document.body or document.getElementById('container');. Read more about jQuery's event delegation