Created
June 9, 2021 08:33
-
-
Save jackyef/cfe7fbbcc17f297b1a8746222f0d3218 to your computer and use it in GitHub Desktop.
Snippet showing that dispatching keydown events programmatically doesn't trigger click.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
button = document.createElement('button') | |
button.onclick = function() { console.log('you clicked me!') } | |
button.dispatchEvent(new Event('click')) | |
button.addEventListener('keydown', e => { | |
console.log('I received a keydown event', e.key) | |
}) | |
function aKeyboardEvent() { | |
var keyboardEvent = new KeyboardEvent('keydown', { | |
key: 'a', | |
code: 'KeyA', | |
which: 65 | |
}); | |
return keyboardEvent; | |
} | |
function enterKeyboardEvent() { | |
var keyboardEvent = new KeyboardEvent('keydown', { | |
key: 'Enter', | |
code: 'Enter', | |
which: 13 | |
}); | |
return keyboardEvent; | |
} | |
function spaceKeyboardEvent() { | |
var keyboardEvent = new KeyboardEvent('keydown', { | |
key: ' ', | |
code: 'Space', | |
which: 32 | |
}); | |
return keyboardEvent; | |
} | |
button.dispatchEvent(aKeyboardEvent()) | |
button.dispatchEvent(enterKeyboardEvent()) | |
button.dispatchEvent(spaceKeyboardEvent()) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment