Skip to content Skip to sidebar Skip to footer

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

Solution 1:

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.

Solution 2:

var target = document;//<--(insert your target here);if(document.createEvent){
  var clickEvent = document.createEvent("MouseEvents");
  clickEvent.initMouseEvent("click", true, true, window, 
    0, 0, 0, 0, 0, false, false, false, 0, null);
  target.dispatchEvent(clickEvent);
}
else{
  target.fireEvent("onclick");
}

Taken from the MDC event.initMouseEvent reference and this SO question.

jsFiddle that you can test on different browsers.

Solution 3:

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

functionperformClick(node) {
    var evt = document.createEvent("MouseEvents");
    evt.initEvent("mousedown", true, true);
    document.getElementById("myElement").dispatchEvent(evt);
}

Solution 4:

Given:

<inputtype="button"id="myButton" onclick="alert('hello world');"/>

The following would invoke the hello world prompt:

document.getElementById("myButton").click();

Post a Comment for "Javascript Cross-browser Click On A Html Dom Element"