'undefined' is not a function evaluating el.click() in Safari

If you take a look at the HTML DOM Level 2 Specification, the click() function is only defined for HTMLInputElement, so while certainly not very user-friendly Safari doesn't need to implement that.

The correct way to trigger an event for modern browsers is in DOM Level 3 Events:

// First create an event
var click_ev = document.createEvent("MouseEvents");
// initialize the event
click_ev.initEvent("click", true /* bubble */, true /* cancelable */);
// trigger the event
document.getElementById("someElement").dispatchEvent(click_ev);

Here's jsfiddle that works in Chrome, Safari, Firefox and IE9: http://jsfiddle.net/y5yW9/6/


You're triggering a click event on a divwhich would have no implicit click handler.


I came across this same issue while working on a similar problem. What I came up with is the following for triggering click events in safari(as well as other browsers, of course):

var t = document.getElementById('someidhere');
if (document.dispatchEvent) {
    var e = new MouseEvent('click', {
        view: window,    // Window associated with the event
        bubbles: true,
        cancelable: true
    });
    t.dispatchEvent(e);
} else if (document.fireEvent) {
    t.fireEvent('onclick');
} else if (t.click) {
    t.click();
}

According to @Dennis, your code already works for Firefox, however this code should work in Firefox anyway as of version 79.0(the version it was tested in).

Note that initEvent() has been deprecated. The new method of creating the event through the Event constructor doesn't work in Internet Explorer, however.

Tags:

Javascript