I need to simulate a click on a link using JavaScript. Could anybody tell me how it can be achieved? It should work in FireFox and IE.
Thanks in advance.
The HTMLElement. click() method simulates a mouse click on an element. When click() is used with supported elements (such as an <input> ), it fires the element's click event. This event then bubbles up to elements higher in the document tree (or event chain) and fires their click events.
The JavaScript to click it: document. getElementById("my-link-element"). click();
Answer: Use the jQuery click() Method You can use the click() method to trigger a click on a link programmatically using jQuery.
To add the click event in React using plain JavaScript, you need to use addEventListener() to assign the click event to an element. Create one <button> element as ref props so that it can be accessed to trigger the click event.
var el = document.getElementById('link');
// Firefox
if (document.createEvent) {
var event = document.createEvent("MouseEvents");
event.initEvent("click", true, true);
el.dispatchEvent(event);
}
// IE
else if (el.click) {
el.click();
}
example
As mentioned by others, you can use click
method for IE. For Firefox, have a look at element.dispatchEvent. See the example in the documentation.
this should do the trick
document.getElementById('yourLink').click();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With