Home > OS >  Trigger the enter key on button click
Trigger the enter key on button click

Time:11-08

I've seen solutions to triggering a button when hitting the enter key, but what I would like to achieve is the opposite. How can I trigger the enter key on button click using JS?

const triggerEnterKey = () => {
  ...
}
<button onClick={()=> {triggerEnterKey()}}>Trigger enter key</button>

CodePudding user response:

Please try this.

var evt = new KeyboardEvent('keydown', {'keyCode':13, 'which':13}); 
const textTag = document.getElementById("text");                         
                            
window.addEventListener('click', () => {
    document.dispatchEvent (evt); 
  textTag.innerHTML = "Enter was presseed";
});                      
<h1>Simulate enter press on click</h1>
<p id="text"></p>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

Use dispatchEvent to dispatch a

new KeyboardEvent('keydown',{'key':'Enter'})
  • Related