admin管理员组

文章数量:1327661

HTML button that when pressed simulates an ESC keyboard key pressed. So clicking the button would have the same effect as user pressing ESC key on their keyboard

If it is certainly not possible in any way please tell me.

Any method is fine.

EDIT: I don't want pressing ESC key to trigger something, I want the reverse, something that triggers ESC key

HTML button that when pressed simulates an ESC keyboard key pressed. So clicking the button would have the same effect as user pressing ESC key on their keyboard

If it is certainly not possible in any way please tell me.

Any method is fine.

EDIT: I don't want pressing ESC key to trigger something, I want the reverse, something that triggers ESC key

Share Improve this question edited Oct 29, 2021 at 6:59 Ahmet Emre Kilinc 6,93519 gold badges36 silver badges47 bronze badges asked Mar 29, 2014 at 6:22 FriedpansellerFriedpanseller 6993 gold badges17 silver badges33 bronze badges 6
  • You have an event that is listening to the ESC key and you want to trigger it? Is that it? – acdcjunior Commented Mar 29, 2014 at 6:25
  • Dear you should read this answers carefully. stackoverflow./questions/9230308/… – Muhammad Irfan Commented Mar 29, 2014 at 6:25
  • And what should pressing the escape button do? You can't simulate keypress events that are handled by the browser or operating system, only keypress events that are handled by javascript itself (or native events). – adeneo Commented Mar 29, 2014 at 6:30
  • @Muhammad I dont understand the code in that link – Friedpanseller Commented Mar 29, 2014 at 6:57
  • Did You Check Any Of The Fiddle Below??? – Kiranramchandran Commented Mar 29, 2014 at 7:08
 |  Show 1 more ment

3 Answers 3

Reset to default 4

Try This Code

JS

$('body').keydown(function(e){
    if (e.which==27){
        alert("hh");
    }

});

$('#trigger').click(function(){
    var e=$.Event('keydown');
    e.which=27;
    $('body').trigger(e);
});

HTML

<input type="button" id="trigger" value="trigger button" />

DEMO HERE

using JQuery you can Create Key Press Event and bind that Event with Button Click. Like:

<input type="button" id="esc" value="Esc like button">


<script>
$('body').keydown(function(e) {
    if (e.keyCode == 27) {
        // put your code here if any (that will run after Esc pressed).
        alert('Esc Pressed');
    }    
});

var e = $.Event("keydown", {
    keyCode: 27
});

$('#esc').click(function() {
    $("body").trigger(e);
});
</script>

Fiddle DEMO

One can dispatch the keyboard event by creating an event instance and then dispatching it on the window.

// following for keyboard key down event for "a"
const event = new KeyboardEvent('keydown', {code: 'KeyA', key: 'a'})
window.dispatchEvent(event)

The point to note is that the event dispatched will not be a trusted event when listened.

本文标签: javascriptPress escape key on keyboard with html buttonStack Overflow