Pregunta

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.

¿Fue útil?

Solución

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.

Otros consejos

Have you tried e.preventDefault();?

Or a better alternative - pick a different combination. Users typically don't like it when you start messing with their key bindings. On many sites (trello and github come to mind), there are no control keys at all. You can invoke special functionality just by typing a single character (on github "t" opens a page where you can type a filename and it will filter files in your repository). And in most cases that should be fine. You don't typically need to be able to type things on the html body. You would just want to make sure they're not inside an input or textarea before you fire the functionality.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top