Trigger a button click from a non-button element

Viewed 59731

How would you trigger a click event from an element that supposedly does not have native clickable behaviours?

For example, I know that you could simply just use the following:

document.getElementById('x').click();

But what happens if 'x' is a 'DIV'? I have an implementation, and it doesn't seem to trigger... I get the error (chrome 12):

Uncaught TypeError: Object #<HTMLDivElement> has no method 'click'

Ideas?

Quick Edit - I'm looking for vanilla JS here... I like reinventing the wheel in my image... :-)

7 Answers

Vanilla JS (without jQuery)

/**
 * Simulate a click event.
 * @public
 * @param {Element} elem  the element to simulate a click on
 */
var simulateClick = function (elem) {
    // Create our event (with options)
    var evt = new MouseEvent('click', {
        bubbles: true,
        cancelable: true,
        view: window
    });
    // If cancelled, don't dispatch our event
    var canceled = !elem.dispatchEvent(evt);
};

To use it, call the function, passing in the element you want to simulate the click on.

var someLink = document.querySelector('a');
simulateClick(someLink);

https://gomakethings.com/how-to-simulate-a-click-event-with-javascript/

Related