Nok Imchen Nok Imchen - 4 months ago 28
Javascript Question

How to simulate a mouse click using JavaScript?

I know about the
method. However, I'd like to know how to simulate the onclick event.

I found this code somewhere here on Stack Overflow, but I don't know how to use it :(

function contextMenuClick()
var element= 'button'

var evt = element.ownerDocument.createEvent('MouseEvents');

evt.initMouseEvent('contextmenu', true, true,
element.ownerDocument.defaultView, 1, 0, 0, 0, 0, false,
false, false, false, 1, null);


How do I fire a mouse click event using JavaScript?


(Modified version to make it work without prototype.js)

function simulate(element, eventName)
    var options = extend(defaultOptions, arguments[2] || {});
    var oEvent, eventType = null;

    for (var name in eventMatchers)
        if (eventMatchers[name].test(eventName)) { eventType = name; break; }

    if (!eventType)
        throw new SyntaxError('Only HTMLEvents and MouseEvents interfaces are supported');

    if (document.createEvent)
        oEvent = document.createEvent(eventType);
        if (eventType == 'HTMLEvents')
            oEvent.initEvent(eventName, options.bubbles, options.cancelable);
            oEvent.initMouseEvent(eventName, options.bubbles, options.cancelable, document.defaultView,
            options.button, options.pointerX, options.pointerY, options.pointerX, options.pointerY,
            options.ctrlKey, options.altKey, options.shiftKey, options.metaKey, options.button, element);
        options.clientX = options.pointerX;
        options.clientY = options.pointerY;
        var evt = document.createEventObject();
        oEvent = extend(evt, options);
        element.fireEvent('on' + eventName, oEvent);
    return element;

function extend(destination, source) {
    for (var property in source)
      destination[property] = source[property];
    return destination;

var eventMatchers = {
    'HTMLEvents': /^(?:load|unload|abort|error|select|change|submit|reset|focus|blur|resize|scroll)$/,
    'MouseEvents': /^(?:click|dblclick|mouse(?:down|up|over|move|out))$/
var defaultOptions = {
    pointerX: 0,
    pointerY: 0,
    button: 0,
    ctrlKey: false,
    altKey: false,
    shiftKey: false,
    metaKey: false,
    bubbles: true,
    cancelable: true

You can use it like this:

simulate(document.getElementById("btn"), "click");

Note that as a third parameter you can pass in 'options'. The options you don't specify are taken from the defaultOptions (see bottom of the script). So if you for example want to specify mouse coordinates you can do something like:

simulate(document.getElementById("btn"), "click", { pointerX: 123, pointerY: 321 })

You can use a similar approach to override other default options.

Credits should go to kangax. Here's the original source (prototype.js specific).