[javascript] 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:

<script type="text/javascript">
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);
    }
}
</script>

<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?

This question is related to javascript

The answer is


What about something simple like:

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

Supported even by IE.


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

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


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

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

const Discord = require("discord.js");
const superagent = require("superagent");

module.exports = {
    name: "hug",
    category: "action",
    description: "hug a user!",
    usage: "hug <user>",
    run: async (client, message, args) => {
    let hugUser = message.mentions.users.first() 
    if(!hugUser) return message.channel.send("You forgot to mention somebody.");
    let hugEmbed2 = new Discord.MessageEmbed()
    .setColor("#36393F")
    .setDescription(`**${message.author.username}** hugged **himself**`)
    .setImage("https://i.kym-cdn.com/photos/images/original/000/859/605/3e7.gif")
     .setFooter(`© Yuki V5.3.1`, "https://cdn.discordapp.com/avatars/489219428358160385/19ad8d8c2fefd03fa0e1a2e49a2915c4.png")
  if (hugUser.id === message.author.id) return message.channel.send(hugEmbed2);
    const {body} = await superagent
    .get(`https://nekos.life/api/v2/img/hug`);

    let hugEmbed = new Discord.MessageEmbed()
    .setDescription(`**${message.author.username}** hugged **${message.mentions.users.first().username}**`)
    .setImage(body.url)
    .setColor("#36393F")
     .setFooter(`© Yuki V5.3.1`, "https://cdn.discordapp.com/avatars/489219428358160385/19ad8d8c2fefd03fa0e1a2e49a2915c4.png")
    message.channel.send(hugEmbed)
}
}

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


document.getElementById("#elment").click()

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


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:

_x000D_
_x000D_
let theclick = new Event("dblclick")

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

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


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

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