431

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?

BinaryButterfly
  • 18,137
  • 13
  • 50
  • 91
Belgin Fish
  • 19,187
  • 41
  • 102
  • 131
  • 2
    See http://stackoverflow.com/questions/1421584/how-can-i-simulate-a-click-to-an-anchor-tag – Crescent Fresh Apr 24 '10 at 18:33
  • 12
    "Five Most Common Coding Errors": http://javascript.about.com/od/hintsandtips/a/worst_4.htm - Just about no one runs IE4 any more and so support for the document.all DOM is no longer required. It is really surprising though how many people still use it in their coding. Worse is that support for the document.all DOM is often tested for in order to determine the browser being used and if it is supported then the code assumes that the browser is Internet Explorer (which is completely wrong usage since **Opera** also recognises that DOM). – zaf Apr 24 '10 at 18:14
  • The problem with most of these solutions is that the element being click won't be focused as it normally would had a user clicked it with their cursor. But simply adding element.focus() would fix that. – Jordan Dec 05 '22 at 22:38
  • @zaf that link is down and will go to a 404 now, but the wayback is here. The article in question is very good. https://web.archive.org/web/20150906012912/http://javascript.about.com/od/hintsandtips/a/worst_4.htm – Hermanboxcar Jun 26 '23 at 05:48

14 Answers14

616

What about something simple like:

document.getElementById('elementID').click();

Supported even by IE.

mb21
  • 34,845
  • 8
  • 116
  • 142
StudioTime
  • 22,603
  • 38
  • 120
  • 207
  • 1
    @HermannIngjaldsson Yes it works perfectly in IE - http://msdn.microsoft.com/en-us/library/ie/ms536363%28v=vs.85%29.aspx – StudioTime Jan 06 '15 at 16:43
  • 8
    The question was "does it work in ie as well?" - the answer is yes - AFAIK at least down to 8, haven't checked 7 – StudioTime Apr 06 '15 at 16:06
  • 45
    Did this not exist before? Why did the 2010 answers not mention this simple solution? Just curious... – Parth Feb 22 '16 at 16:32
  • It is not recent, but it doesn't work on very old Firefox versions (before Firefox 5). Look at https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/click – Arnaud Jeansen Dec 16 '16 at 14:04
  • 4
    @NinoŠkopac Works great currently for desktop but no guarantee to work with mobile browsers. Even the mozilla developer site doesn't show mobile support. – le0diaz Dec 21 '16 at 21:20
  • May help someone: when using this to 'click' an faq item linked to in the url (e.g. /faq#item-1), I needed to use: setTimeout(function(){ document.getElementById(hash).click(); }, 300); – timhc22 May 29 '18 at 15:13
  • 51
    @Parth Maybe it did, it just didn't *click* for them. – Andrew Jul 29 '19 at 16:36
  • The only thing is don't try to replace getElementById with querySelector it is not the same. – Rahul Sonwanshi Jan 27 '20 at 21:12
  • 1
    @RahulSonwanshi just tried `document.querySelector('#auth_modal .close').click()` on my website and it worked just fine – ddruganov Sep 17 '20 at 10:24
  • It doesn't work for me in Chrome. If I have an element and I do `.click`, the browser console tells me that this is a function. If I do `.click()` with parenthesis then it returns undefined and nothing is clicked on the page. – Aaron Franke Oct 08 '21 at 23:39
  • @AaronFranke Interesting. I tried Chrome on my use case and `.click()` seemed fine. Same with mobile chrome. I was using it on a radio button label. – CubicInfinity Feb 04 '22 at 22:10
  • Isn't working in Chrome. – Hakanai Aug 21 '22 at 06:48
520

[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);
  }
}
KooiInc
  • 119,216
  • 31
  • 141
  • 177
  • I'm not sure how to use this function on a web page (since it's being shown out of context). Can you post an example usage? – Anderson Green Mar 19 '13 at 03:15
  • 12
    @Anderson Green: I have added an example to this jsfiddle: http://jsfiddle.net/KooiInc/W4BHD/ – KooiInc Mar 19 '13 at 06:21
  • 5
    Proof that this works (in Chromium): +1 with `document.querySelector('[value="2706236"]').nextSibling.nextSibling.dispatchEvent(ev);` :) – PointedEars Mar 10 '14 at 20:23
  • [`fireEvent` is a host object's method in the MSHTML DOM](http://msdn.microsoft.com/en-us/library/ie/ms536423(v=vs.85).aspx), though, so the usual caveats apply (do not use type-converting tests, but something along [`isHostMethod()`](http://PointedEars.de/wsvn/JSX/trunk/object.js) instead). – PointedEars Mar 10 '14 at 20:27
  • Can anyone, please, explain (or better write a code) how this answer is applied in the OP's original code posted in his question? Where does the control (the button) get specified? – brilliant Jul 13 '14 at 16:14
  • @KooiInc - WOW!!! **KooiInc**, thank you so much! Yes, I think now I can gasp it. Thank you for your time. – brilliant Jul 14 '14 at 09:31
  • 95
    Well I tried your java-script on the vote up button :) (worked of-course) – 0fnt Oct 16 '14 at 03:47
  • Chrome: A DOM event generated from JavaScript has triggered a default action inside the browser. This behavior is non-standard and will be removed in M53, around September 2016. See https://www.chromestatus.com/features/5718803933560832 for more details. – M H Aug 26 '16 at 19:01
  • 1
    To simulate exact user behavior, you should wrap the `dispatchEvent` or `click` invocations with `setTimeout`, as it appears that `dispatchEvent` is [synchronous](http://stackoverflow.com/a/22924862/3952799). – Lev Kazakov Nov 29 '16 at 21:49
  • ^^ This can have some implications e.g in the case that you simulate user clicks in your tests, and the click event handler performs some async logic. – Lev Kazakov Nov 29 '16 at 21:57
  • Does this work on older mobile devices? I've heard old versions of android don't support `myElement.click();`. Anyway does this work in all browsers? – Will Brickner Dec 26 '16 at 07:31
  • This worked for me BUT I had to do an extra step : let's say the link element is in the variable 'a', I had to do `eventFire(a, 'mouseover'); eventFire(a, 'click');` as a security prevented the click to work without an onmouseover before. – Shautieh Mar 02 '17 at 06:19
  • 23
    `Event.initEvent` is now **deprecated** https://developer.mozilla.org/en/docs/Web/API/Event/initEvent – artnikpro Mar 02 '17 at 11:39
  • @PointedEars I think this is a bit better form for your upvote thing: `document.querySelector('[value="2706236"]').nextSibling.nextSibling.click()` – Alfredo Gallegos Aug 15 '17 at 20:55
  • @AlfredoGallegos In which way is that “a bit better”? – PointedEars Aug 22 '17 at 12:53
  • 1
    If somebody tried to run your snippet without the same context as the post above with the ev event, the code will not work. It's a bit cleaner and more legible to just do `.click()` :) – Alfredo Gallegos Aug 22 '17 at 19:19
  • @AlfredoGallegos You are not making sense. Have you even read the question and the answer in which context I made my *comment*? Also, while `.click()` might be more _readable_, it is _not_ “a bit cleaner”. To begin with, [`.click()` was *proprietary* before HTML5](https://www.w3.org/TR/2003/REC-DOM-Level-2-HTML-20030109/html.html#ID-48250443). – PointedEars Aug 27 '17 at 04:44
  • Can you explain the "if" statement? What is it for? – Nathan B Apr 15 '19 at 10:41
  • see the below answer. .click() works all the way back to IE 6 (without jQuery) – Chris Hawkes Jul 17 '19 at 15:22
  • just remove this as the answer already - it's ridiculous to keep an answer like this when the clear answers are below. NO-ONE is going to use this answer when they can simply... $("#mytest1").click(); – TV-C-1-5 Aug 02 '21 at 23:21
  • Weird how the "you" branch never fires though. What's the deal with that? – Hakanai Aug 21 '22 at 06:53
  • @Hakanai What makes you think it *should* fire? – KooiInc Aug 21 '22 at 06:57
  • 1
    @KooiInc the branch exists in the code. – Hakanai Aug 21 '22 at 07:00
  • I made it easier to figure out what was meant to happen. https://stackblitz.com/edit/js-rf8tyr – Hakanai Aug 21 '22 at 07:14
  • @Hakanai ``-elements are *not* handled in the snippet, but of course you can create custom handlers for that too. Maybe this [stackblitz fork](https://stackblitz.com/edit/js-7ovfb6?file=index.js) clarifies it somewhat more. – KooiInc Aug 21 '22 at 11:20
83

Have you considered using jQuery to avoid all the browser detection? With jQuery, it would be as simple as:

$("#mytest1").click();
BradBrening
  • 5,418
  • 25
  • 30
  • 22
    This only fire jQuery event handlers, not the default behavior (browser goes to href in that case) – Romuald Brunet Aug 22 '12 at 13:26
  • 12
    I don't know about sad but it sure can be convenient to not have to keep recoding the same browser detection routines time and again. – BradBrening May 13 '13 at 20:43
  • 10
    @ErikAigner: I was wondering the same, but glad that the accepted answer in this case is plain JavaScript and not jQuery. Seen that too many times on SO. Once more: jQuery is JavaScript, but JavaScript is not jQuery. Although I like to use jQuery, I'm seeing more and more that devs don't understand the real plain thing. My 2 cents, couldn't resist to comment. ;) – Sander Aug 05 '13 at 13:22
  • 67
    There are also a lot of humans that wouldn't know where to start if they had to wash their clothes by hand, since the majority of households own a washer, and almost as many have a clothes dryer. jQuery, much like modern appliances, have made an old chore much easier and less error prone. It's not the solution for everyone, however, downvoting an answer that accurately answers the question using more concise, understandable syntax while being cross-browser compatible seems backwards. +1. – FreeAsInBeer Dec 16 '13 at 20:10
  • There is nothing sad about choosing the easiest way. In this case however, the answer was not appropriate and should get removed. – Anders Lindén Apr 12 '16 at 07:14
  • 5
    @FreeAsInBeer Then you also shouldn't walk anywhere since driving is so much easier. But we know that's silly. You walk if you don't need to go far. You use plain JavaScript if you need to do something simple and don't want to load an entire library to do it. No need to waste gas/bandwitdth for something simple. – Jacob Mar 02 '17 at 14:24
  • @FreeAsInBeer But is `$("#mytest1").click();` "more concise, understandable syntax" than `document.getElementById('mytest1').click();`? – user1717828 Aug 24 '20 at 10:38
  • 1
    @Jacob Yes but now we have electric scooters so then why not use javascript (Being walking) and then have flying cars (Being Python). Because the road (Being HTML) is like a river (The river of course being the internet). When you finally hit a deer (Console Errors) you may not know how to fix it so you use a mechanic (Stack Overflow). Do you follow. – MomasVII Feb 15 '22 at 23:44
31
var elem = document.getElementById('mytest1');

// Simulate clicking on the specified element.
triggerEvent( elem, 'click' );

/**
 * Trigger the specified event on the specified element.
 * @param  {Object} elem  the target element.
 * @param  {String} event the type of the event (e.g. 'click').
 */
function triggerEvent( elem, event ) {
  var clickEvent = new Event( event ); // Create the event.
  elem.dispatchEvent( clickEvent );    // Dispatch the event.
}

Reference

mnishiguchi
  • 2,051
  • 23
  • 17
  • 4
    I believe this should be the best answer nowadays – DavidTaubmann Aug 06 '19 at 20:14
  • 1
    Nowadays it's easier to simply do `element.click();`. Most major browsers support this. See https://stackoverflow.com/a/25806894/470749 and https://stackoverflow.com/a/2381612/470749 – Ryan Aug 31 '20 at 20:40
  • This is the answer that works for me, It triggers a click event like the way a user click on a browser, not calling an onclick event on the target like `element.click();` – hugholousk Jan 05 '23 at 16:48
15

You could save yourself a bunch of space by using jQuery. You only need to use:

$('#myElement').trigger("click")
Adam Salma
  • 1,746
  • 1
  • 11
  • 22
8

The top answer is the best! However, it was not triggering mouse events for me in Firefox when etype = 'click'.

So, I changed the document.createEvent to 'MouseEvents' and that fixed the problem. The extra code is to test whether or not another bit of code was interfering with the event, and if it was cancelled I would log that to console.

function eventFire(el, etype){
  if (el.fireEvent) {
    el.fireEvent('on' + etype);
  } else {
    var evObj = document.createEvent('MouseEvents');
    evObj.initEvent(etype, true, false);
    var canceled = !el.dispatchEvent(evObj);
    if (canceled) {
      // A handler called preventDefault.
      console.log("automatic click canceled");
    } else {
      // None of the handlers called preventDefault.
    } 
  }
}
Nate Barbettini
  • 51,256
  • 26
  • 134
  • 147
brianlmerritt
  • 2,644
  • 1
  • 34
  • 39
8

In javascript grab element by its id or class name and then apply .click() to make click happens like:

document.getElementById("btnHandler").click();
Ahmet Emre Kilinc
  • 5,489
  • 12
  • 30
  • 42
  • 1
    Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Sep 21 '22 at 13:09
  • Bad bot! Simplest, fastest, working solution. – Dan Rayson Oct 10 '22 at 21:50
6

Simulating an event is similar to creating a custom event. To simulate a mouse event

  • we gonna have to create MouseEvent using document.createEvent().
  • Then using initMouseEvent(), we've to set up the mouse event that is going to occur.
  • Then dispatched the mouse event on the element on which you'd like to simulate an event.

In the following code, I've used setTimeout so that the button gets clicked automatically after 1 second.

const div = document.querySelector('div');

div.addEventListener('click', function(e) {
  console.log('Simulated click');
});

const simulatedDivClick = document.createEvent('MouseEvents');

simulatedDivClick.initEvent(
  'click', /* Event type */
  true, /* bubbles */
  true, /* cancelable */
  document.defaultView, /* view */
  0, /* detail */
  0, /* screenx */
  0, /* screeny */
  0, /* clientx */
  0, /* clienty */
  false, /* ctrlKey */
  false, /* altKey */
  false, /* shiftKey */
  0, /* metaKey */
  null, /* button */
  null /* relatedTarget */
);

// Automatically click after 1 second
setTimeout(function() {
  div.dispatchEvent(simulatedDivClick);
}, 1000);
<div> Automatically click </div>
DecPK
  • 24,537
  • 6
  • 26
  • 42
4
document.getElementById('elementId').dispatchEvent(new MouseEvent("click",{bubbles: true, cancellable: true}));

Follow this link to know about the mouse events using Javascript and browser compatibility for the same

https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent#Browser_compatibility

geisterfurz007
  • 5,292
  • 5
  • 33
  • 54
3

Use timeout if the event is not getting triggered

setTimeout(function(){ document.getElementById('your_id').click(); }, 200); 
2
document.getElementById("element").click()

Simply select the element from the DOM. The node has a click function, which you can call.

Or

document.querySelector("#element").click()
DerpyCoder
  • 127
  • 1
  • 6
2

Honestly none of the answers here worked for my specific case. jquery was out of the question so all those answers are untested. I will say I built this answer up from @mnishiguchi answer above but this was the only thing that actually ended up working.

// select the element by finding the id of mytest1
const el = document.querySelector('#mytest1');

// pass the element to the simulateClick function
simulateClick( el );

function simulateClick(element){
    trigger( element, 'mousedown' );
    trigger( element, 'click' );
    trigger( element, 'mouseup' );

    function trigger( elem, event ) {
      elem.dispatchEvent( new MouseEvent( event ) );
    }
}
Dharman
  • 30,962
  • 25
  • 85
  • 135
cigol on
  • 337
  • 3
  • 12
0

This isn't very well documented, but we can trigger any kinds of events very simply.

This example will trigger 50 double click on the button:

let theclick = new Event("dblclick")

for (let i = 0;i < 50;i++){
  action.dispatchEvent(theclick) 
}
<button id="action" ondblclick="out.innerHTML+='Wtf '">TEST</button>
<div id="out"></div>

The Event interface represents an event which takes place in the DOM.

An event can be triggered by the user action e.g. clicking the mouse button or tapping keyboard, or generated by APIs to represent the progress of an asynchronous task. It can also be triggered programmatically, such as by calling the HTMLElement.click() method of an element, or by defining the event, then sending it to a specified target using EventTarget.dispatchEvent().

https://developer.mozilla.org/en-US/docs/Web/API/Event

https://developer.mozilla.org/en-US/docs/Web/API/Event/Event

NVRM
  • 11,480
  • 1
  • 88
  • 87
0

The solution that worked for me.... Click event can be called on clicking the button or do it from JavaScript file. In this code either click on the button to show alert or simply call it on some condition or without condition

    function ss(){
    alert('dddddddddddddddddddddddd');
    }
    var mybtn=document.getElementById('btn');
    mybtn.click();
    <!DOCTYPE html>
    <html>
    <head>
    <title>Page Title</title>
    </head>
    <body>
    
    <h1>This is a Heading</h1>
    <p>This is a paragraph.</p>
    <button id="btn" onclick="ss()">click to see </button>
    </body>
    </html>
Zia Khan
  • 188
  • 2
  • 9