Explore Courses Blog Tutorials Interview Questions
0 votes
in Java by (13.1k points)

Can anyone help me how I can able to simulate the mouse click event on JavaScript? I was following the below code, but was not able to fire the mouse click event.

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



Any help would be appreciated.

1 Answer

0 votes
by (26.7k points)

You can use the below code to simulate it properly:

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


Also, in able to use you can use the below function:

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

I hope this will help.

Want to know more about Java? Prefer this tutorial on Java Tutorial.

Want to become a Java Expert? Join Java Course now!!

Related questions

Browse Categories