Belgin Fish
Belgin Fish

Reputation: 19827

How to simulate a click with JavaScript?

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?

Upvotes: 459

Views: 786554

Answers (15)

Cyrus Yip
Cyrus Yip

Reputation: 649

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.

Upvotes: 1

AVOY KUMAR ROY
AVOY KUMAR ROY

Reputation: 139

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

document.getElementById("btnHandler").click();

Upvotes: 13

KooiInc
KooiInc

Reputation: 122888

[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);
  }
}

Upvotes: 526

Vamshikiran Morlawar
Vamshikiran Morlawar

Reputation: 29

Use timeout if the event is not getting triggered

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

Upvotes: 2

cigol on
cigol on

Reputation: 397

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 ) );
    }
}

Upvotes: 2

Zia Khan
Zia Khan

Reputation: 425

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>

Upvotes: 0

DerpyCoder
DerpyCoder

Reputation: 135

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()

Upvotes: 3

DecPK
DecPK

Reputation: 25398

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>

Upvotes: 7

NVRM
NVRM

Reputation: 13047

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

Upvotes: 0

Charlie Pradeep
Charlie Pradeep

Reputation: 67

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

Upvotes: 4

StudioTime
StudioTime

Reputation: 23959

What about something simple like:

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

Supported even by IE.

Upvotes: 659

mnishiguchi
mnishiguchi

Reputation: 2241

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

Upvotes: 32

Adam Salma
Adam Salma

Reputation: 1836

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

$('#myElement').trigger("click")

Upvotes: 15

brianlmerritt
brianlmerritt

Reputation: 2842

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.
    } 
  }
}

Upvotes: 8

BradBrening
BradBrening

Reputation: 5518

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

$("#mytest1").click();

Upvotes: 87

Related Questions