I’m just wondering how I can use JavaScript to simulate a click on an element.
Currently I have:
function simulateClick(control) { if (document.all) { control.click(); } else { var evObj = document.createEvent('MouseEvents'); evObj.initMouseEvent('click', true, true, window, 1, 12, 345, 7, 220, false, false, true, false, 0, null ); control.dispatchEvent(evObj); } }
<a href="http://www.google.com" id="mytest1">test 1</a><br> <script type="text/javascript"> simulateClick(document.getElementById('mytest1')); </script>
But it’s not working 🙁
Any ideas?
Advertisement
Answer
[Edit 2022] The answer was really outdated. Modernized it. The original answer is at the bottom.
Use element.dispatchEvent
with a freshly created Event
of the desired type.
Here’s an example using event delegation.
Fork this stackblitz project to play around with it.
// Note: {bubbles: true} because of the event delegation ... document.addEventListener(`click`, handle); document.addEventListener(`virtualhover`, handle); // the actual 'trigger' function const trigger = (el, etype, custom) => { const evt = custom ?? new Event( etype, { bubbles: true } ); el.dispatchEvent( evt ); }; // a custom event ;) const vHover = new CustomEvent(`virtualhover`, { bubbles: true, detail: `red` }); setTimeout( _ => trigger( document.querySelector(`#testMe`), `click` ), 1000 ); function handle(evt) { if (evt.target.id === `clickTrigger`) { trigger(document.querySelector(`#testMe`), `click`); } if (evt.type === `virtualhover`) { evt.target.style.color = evt.detail; return setTimeout( _ => evt.target.style.color = ``, 1000 ); } if (evt.target.id === `testMe`) { document.querySelector(`#testMeResult`) .insertAdjacentHTML(`beforeend`, `<p>One of us clicked #testMe. It was <i>${evt.isTrusted ? `<b>you</b>` : `me`}</i>.</p>`); trigger( document.querySelector(`#testMeResult p:last-child`), `virtualhover`, vHover ); } }
body { font: 1.2rem/1.5rem verdana, arial; margin: 2rem; } #testMe { cursor: pointer; } p { margin: 0.2rem 0; }
<div id="testMe"> Test me can be clicked </div> <p><button id='clickTrigger'>Click #testMe</button></p> <div id="testMeResult"></div>
The old answer:
Here’s what I cooked up. It’s pretty simple, but it works:
function eventFire(el, etype){ if (el.fireEvent) { el.fireEvent('on' + etype); } else { var evObj = document.createEvent('Events'); evObj.initEvent(etype, true, false); el.dispatchEvent(evObj); } }