1

I want that when TAB key is pressed to execute my code and e.preventDefault();. For testing I have checked the below events with only alert(9);:

$().ready(function(){
    $("div").delegate(".note","keydown",function(e){
        //not working
    });

    $("div").delegate(".note","keypress",function(e){
        //not working
    });

    $("div").delegate(".note","click",function(e){
        //working fine
    });
});

Only click event works while keypress and keydown doesn't work.

YakovL
  • 7,557
  • 12
  • 62
  • 102
Your Yummy
  • 153
  • 1
  • 6
  • 20

3 Answers3

2

Actually, keydown and keypress have the target of body unless an element is in focus:

When an element is focused, key events received by the document must be targeted at that element. There may be no element focused; when no element is focused, key events received by the document must be targeted at the body element.

source: https://www.w3.org/TR/html50/editing.html#focus

So the problem is not delegating itself but rather making an element focusable (your handlers just don't fire!). For an arbitrary element to be able to recieve focus, use the tabindex attribute for the elements that are supposed to have key event handlers (learn more here).

YakovL
  • 7,557
  • 12
  • 62
  • 102
0

Something like this will work if ".note" in an element that accepts focus.

JS

$(function(){
   $("div").delegate(".note","keydown",function(e){
       if(e.originalEvent.keyCode == 9){
           console.log('Tada!');
           e.preventDefault();
       }
    });
});

See: http://jsfiddle.net/fcEx5/

Matt Rohland
  • 706
  • 10
  • 19
0

Check out this implementation, it is a little bit more complex than what you asked but you can leverage it, it uses on() instead of delegate() which is recommended :

<button id="myButton"> Click Me </button>
<input type="text" id="myText" />

the js

function myFunction(){
     alert("hi!");
}



$(document).ready(function(){

    $("#myButton").on("click",myFunction);
    $("#myText").on("keydown",function(e){
        var keyCode = e.keyCode || e.which; 
        if (keyCode == 9) { 
            e.preventDefault(); 
            myFunction();
          } 
    });

});

The TAB button or a click on the button will trigger the function, also some documentation about on()

The .on() method attaches event handlers to the currently selected set of elements in the jQuery object. As of jQuery 1.7, the .on() method provides all functionality required for attaching event handlers.

And finally here is the working demo

isJustMe
  • 5,452
  • 2
  • 31
  • 47