450

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?

4
  • 12
    "Five Most Common Coding Errors": 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, 2010 at 18:14
  • 2
  • 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 5, 2022 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. web.archive.org/web/20150906012912/http://javascript.about.com/… Jun 26, 2023 at 5:48

15 Answers 15

642

What about something simple like:

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

Supported even by IE.

12
  • 1
    @HermannIngjaldsson Yes it works perfectly in IE - msdn.microsoft.com/en-us/library/ie/ms536363%28v=vs.85%29.aspx
    – StudioTime
    Jan 6, 2015 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 6, 2015 at 16:06
  • 45
    Did this not exist before? Why did the 2010 answers not mention this simple solution? Just curious...
    – Parth
    Feb 22, 2016 at 16:32
  • 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, 2016 at 21:20
  • 52
    @Parth Maybe it did, it just didn't click for them.
    – Andrew
    Jul 29, 2019 at 16:36
525

[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);
  }
}
25
  • 12
    @Anderson Green: I have added an example to this jsfiddle: jsfiddle.net/KooiInc/W4BHD
    – KooiInc
    Mar 19, 2013 at 6:21
  • 5
    Proof that this works (in Chromium): +1 with document.querySelector('[value="2706236"]').nextSibling.nextSibling.dispatchEvent(ev); :) Mar 10, 2014 at 20:23
  • 95
    Well I tried your java-script on the vote up button :) (worked of-course)
    – 0fnt
    Oct 16, 2014 at 3:47
  • 1
    To simulate exact user behavior, you should wrap the dispatchEvent or click invocations with setTimeout, as it appears that dispatchEvent is synchronous. Nov 29, 2016 at 21:49
  • 23
    Event.initEvent is now deprecated developer.mozilla.org/en/docs/Web/API/Event/initEvent
    – artnikpro
    Mar 2, 2017 at 11:39
85

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

$("#mytest1").click();
8
  • 22
    This only fire jQuery event handlers, not the default behavior (browser goes to href in that case) Aug 22, 2012 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. May 13, 2013 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 5, 2013 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. Dec 16, 2013 at 20:10
  • 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 2, 2017 at 14:24
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

3
  • 4
    I believe this should be the best answer nowadays Aug 6, 2019 at 20:14
  • 1
    Nowadays it's easier to simply do element.click();. Most major browsers support this. See stackoverflow.com/a/25806894/470749 and stackoverflow.com/a/2381612/470749
    – Ryan
    Aug 31, 2020 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 5, 2023 at 16:48
15

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

$('#myElement').trigger("click")
3
  • 12
    OP asked for JavaScript. Although this is compact and functional, some people prefer no-Library JS over things like jQuery.
    – user3856347
    Jul 30, 2016 at 22:04
  • 59
    Save space by downloading jquery?
    – M H
    Aug 26, 2016 at 19:02
  • @MH I think a more valid argument would be "to keep it simple". Your default profile here in SO is about the same size of jQuery. Dec 14, 2019 at 3:20
10

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

document.getElementById("btnHandler").click();
2
  • 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.
    – Community Bot
    Sep 21, 2022 at 13:09
  • Bad bot! Simplest, fastest, working solution.
    – Dan Rayson
    Oct 10, 2022 at 21:50
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.
    } 
  }
}
0
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>

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

0
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()
4
  • I know. I was in a rush so I did not add an explanation. Sorry about that.
    – DerpyCoder
    Feb 14, 2021 at 20:18
  • You don't use a # when you're getting an element by id. If you want to do that, use query selector, i.e. document.querySelector('#elment').click();.
    – ublec
    Apr 23, 2021 at 22:03
  • Oops made another typo
    – DerpyCoder
    Apr 27, 2021 at 1:38
  • Clear concise answer
    – StefanBob
    Aug 22, 2022 at 17:10
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 ) );
    }
}
2

Use timeout if the event is not getting triggered

setTimeout(function(){ document.getElementById('your_id').click(); }, 200); 
1

This question seems an XY problem. You wanted to simulate a click on an anchor element to load a link, but you can load the link without clicking the anchor element.

const url = document.querySelector("#mytest1").getAttribute("href");
window.location.assign(url);

See location: assign() method - Web APIs | MDN.

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

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>

Not the answer you're looking for? Browse other questions tagged or ask your own question.