Search code examples
javascriptjquerybookmarks

How to get first pick at keydown (preventing "add bookmark" dialog from showing)


I have a checkbox in my jQuery application that you can check to duplicate a <div>. I'd like now to create a Ctrl+D shortcut for the operation. I can sense Ctrl+D with:

$(document).on('keydown',function(e) {  
    debugger;
    if((e.keyCode == 68) && e.ctrlKey){
        $('.duplicate').trigger('click');
    }
});  

But it looks like Firefox is capturing the Ctrl+D first and putting up a dialog to "Edit a bookmark."

How can I get the interrupt first, and then I'll kill it when I'm done? I don't want my users to have to dismiss a Firefox dialog every time they enter Ctrl+D.


Solution

  • Try using e.preventDefault();:

    $(document).on('keydown',function(e) {  
        //debugger;
        if((e.keyCode == 68) && e.ctrlKey){
            $('.duplicate').trigger('click');
            e.preventDefault();
        }
    });  
    

    See demo page here (edit the demo here).

    On a side note, it is not a good usability practice to override widely-known keys/commands. While you can achieve that, it is advisable and better to use another combination of keys.