0

Does someone see in this jsfiddle

Why I'm not getting a keydown interrupt? I get a click interrupt in the orange box but no interrupt if I click in the beige box and then hit a key.

Thanks

$(function () {
    $('#beigeBox').keydown(function(e) {                        
            console.log("In keydown handler");
            if(e.keyCode == 68) {  // 'D'
                console.log("Got 68");
            }
    });

    $('#orangeBox').click(function() {                      
            console.log("orangeBox clicked");
    });

});

2 Answers 2

2

Your beigeBox div is not contenteditable, therefore no keydown events can be registered on it. Your #orangeBox div on the other hand contains a click handler, which does register (since div is clickable).

Here's a demo where your beigeBox will register a keydown, since contenteditable is enabled: http://jsfiddle.net/tymeJV/36Tfx/3/

3
  • Hmmm. Ok, good point! In the real application, though, I have a checkbox that you can click to duplicate a div. What I'm trying to do here is create a Ctrl-D shortcut for it. But the div to be duplicated is not necessarily contenteditable and I don't want to force the user to click in certain place before Ctrl-D works. So is there a way to sense Ctrl-D no matter where the mouse is? (This might be morphing into a new question.)
    – Steve
    Aug 29, 2013 at 22:37
  • 1
    @Steve -- You can do $(document).on('keydown', function(e) { //check the e.which for key }); to catch the keypresses. You'll have to lookup the keycodes tho. Might be a bad idea running a function everytime the user presses a key tho.
    – tymeJV
    Aug 29, 2013 at 22:42
  • Thanks! That works. Well, not quite. There's still a problem with other applications get the Ctrl-D first, but I put that question in a new StackOverflow at stackoverflow.com/questions/18522385/….
    – Steve
    Aug 29, 2013 at 23:13
0

Try this JSfiddle

Code:

$(function () {

    $('#beigeBox').keypress(function(event) {

        alert("In keydown handler");       

        if (event.which == 68) {

            event.preventDefault();
            alert("Got 68");
        }                   
    });

    $('#orangeBox').click(function() {

        alert("orangeBox clicked");

    });

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.