Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I programmatically click on an element in JavaScript?

In IE, I can just call element.click() from JavaScript - how do I accomplish the same task in Firefox? Ideally I'd like to have some JavaScript that would work equally well cross-browser, but if necessary I'll have different per-browser JavaScript for this.

like image 863
Bruce Avatar asked Apr 30 '09 21:04

Bruce


People also ask

How do you click an element in JavaScript?

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.

Can you click on a div JavaScript?

The answer is definitely yes, but you will need to write javascript code for it. We can use a click handler on the div element to make it clickable.

What is click () method?

The click() method simulates a mouse-click on an element. This method can be used to execute a click on an element as if the user manually clicked on it.

How do you click a class in JavaScript?

click(); The method getElementsByClassName() takes a single class-name (rather than document. querySelector() / document. querySelectorAll() , which take a CSS selector), and you passed two (presumably class-names) to the method.


2 Answers

The document.createEvent documentation says that "The createEvent method is deprecated. Use event constructors instead."

So you should use this method instead:

var clickEvent = new MouseEvent("click", {     "view": window,     "bubbles": true,     "cancelable": false }); 

and fire it on an element like this:

element.dispatchEvent(clickEvent); 

as shown here.

like image 136
Iulian Onofrei Avatar answered Sep 29 '22 21:09

Iulian Onofrei


For firefox links appear to be "special". The only way I was able to get this working was to use the createEvent described here on MDN and call the initMouseEvent function. Even that didn't work completely, I had to manually tell the browser to open a link...

var theEvent = document.createEvent("MouseEvent"); theEvent.initMouseEvent("click", true, true, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null); var element = document.getElementById('link'); element.dispatchEvent(theEvent);  while (element) {     if (element.tagName == "A" && element.href != "")     {         if (element.target == "_blank") { window.open(element.href, element.target); }         else { document.location = element.href; }         element = null;     }     else     {         element = element.parentElement;     } } 
like image 26
will Avatar answered Sep 29 '22 22:09

will