Execute Ctrl+D on button click

12.5k views Asked by At

I am trying to mimic key press events, for instance Ctrl+D on a button click.

It would be great if someone can point me in the right direction on how to achieve the same.

4

There are 4 answers

1
FatherStorm On

You're not allowed to do that. Imagine all the havoc I could wreak if I could send CTRL-ALT-DEL at will.

0
Christian On

That would be "firing events", though I'm leaving the exercise to you to find the right code.

As the other guy said, you cannot do any kind of thing with it. It is purposefully limited.

However, let's say I have a wysiwyg editor in javascript, which supports receiving ctrl+s and saving, you should be able to fire that yourself and make it save anyway.

At the end, it's a matter of context (focus), and which sometimes fails (again, purposefully).

1
lonesomeday On

The code for triggering a custom event (in this instance, Ctrl+d) is as follows:

var evt = jQuery.Event("keypress");
evt.keyCode = 100; // d
evt.ctrlKey = true;
$(document).trigger(evt);

NB that, as the other answers have said, this will be limited in its impact. You won't be able to affect normal browser functions in this way.

0
Azam Alvi On

This will trigger ctrl+d

function btnClick(){
    document.dispatchEvent(new KeyboardEvent('keydown', {'key': 'd', 'ctrlKey': true}));   
}