Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simulate a click on a link with JavaScript

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.

like image 910
cycero Avatar asked Dec 13 '10 07:12

cycero


People also ask

How do you trigger a click in JavaScript?

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.

How do I programmatically click a link with JavaScript?

The JavaScript to click it: document. getElementById("my-link-element"). click();

How do you trigger a click?

Answer: Use the jQuery click() Method You can use the click() method to trigger a click on a link programmatically using jQuery.

How do you add a click event to a button with plain JavaScript?

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.


3 Answers

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

like image 59
Anurag Avatar answered Nov 12 '22 20:11

Anurag


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.

like image 20
dheerosaur Avatar answered Nov 12 '22 19:11

dheerosaur


this should do the trick

document.getElementById('yourLink').click();
like image 1
Jinesh Parekh Avatar answered Nov 12 '22 19:11

Jinesh Parekh