Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript Cross-Browser Click on a HTML DOM Element

Is there a vanilla JavaScript cross-browser function available that is able to trigger a click event on a HTML DOM element (including non-form elements like a div)?

like image 756
Samuel Liew Avatar asked Jul 27 '11 01:07

Samuel Liew


People also ask

How do you access and manipulate HTML elements using DOM?

Accessing Elements by IDThe easiest way to access a single element in the DOM is by its unique ID. You can get an element by ID with the getElementById() method of the document object. In the Console, get the element and assign it to the demoId variable. const demoId = document.

Can JavaScript access DOM?

DOM and JavaScript The document as a whole, the head, tables within the document, table headers, text within the table cells, and all other elements in a document are parts of the document object model for that document. They can all be accessed and manipulated using the DOM and a scripting language like JavaScript.

Is click a DOM event?

The onclick event is a DOM event that occurs when a user clicks on an element. The Document Object Model (DOM) is created by the browser when a web page is loaded.


2 Answers

Most who go down this path either end up developing their own event managment system (which isn't that hard but is annoying) or work within the available capabilities.

If all browsers supported a single model, (say the W3C event model), life would be sweet. But they don't. And not only that, some browsers refuse to respond to programmatic events the same way as "real" events. e.g. dispatching a click event using displatchEvent on a link in Firefox will not cause the browser to follow the link (but will trigger the onclick listener if there is one). Most other browsers will follow the link.

IE didn't support dispatchEvent up to version 8 (perhaps 9 does), it has fireEvent which is similar but different.

HTML5 (which is not a standard yet, maybe it never will be) has introduced a click method for the HTMLElement interface, however it's not fully implemented yet and can't be relied upon. It can likely be used for environments where you know or can control the browser versions that will be using the page.

You can also just call the element's onclick property if a listener has been assigned to the property or inline, but of course that's not like a real event.

Useful post on dispatchEvent on clj.

like image 139
RobG Avatar answered Sep 22 '22 19:09

RobG


Found this elusive function on Mozilla documentation: https://developer.mozilla.org/En/DOM/Document.createEvent, and here too: http://javascript.gakaa.com/document-createevent-4-0-5-.aspx

function performClick(node) {
    var evt = document.createEvent("MouseEvents");
    evt.initEvent("mousedown", true, true);
    document.getElementById("myElement").dispatchEvent(evt);
}
like image 21
Samuel Liew Avatar answered Sep 23 '22 19:09

Samuel Liew