¿Cómo simular un clic del mouse usando JavaScript?

Resuelto Nok Imchen asked hace 13 años • 8 respuestas

Conozco el document.form.button.click()método. Sin embargo, me gustaría saber cómo simular el onclickevento.

Encontré este código en algún lugar aquí en Stack Overflow, pero no sé cómo usarlo :(

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

  element.dispatchEvent(evt);
}

¿Cómo activo un evento de clic del mouse usando JavaScript?

Nok Imchen avatar May 28 '11 04:05 Nok Imchen
Aceptado

(Versión modificada para que funcione sin prototipo.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);
        }
        else
        {
            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);
        }
        element.dispatchEvent(oEvent);
    }
    else
    {
        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
}

Puedes usarlo así:

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

Tenga en cuenta que como tercer parámetro puede pasar 'opciones'. Las opciones que no especifica se toman de las Opciones predeterminadas (consulte la parte inferior del script). Entonces, si por ejemplo quieres especificar las coordenadas del mouse, puedes hacer algo como:

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

Puede utilizar un enfoque similar para anular otras opciones predeterminadas.

Los créditos deben ir a kangax . Aqui esta la fuente original (especifica de prototype.js).

TweeZz avatar May 27 '2011 21:05 TweeZz

Una forma más sencilla y estándar de simular un clic del mouse sería utilizar directamente el constructor de eventos para crear un evento y enviarlo.

Aunque el MouseEvent.initMouseEvent()método se mantiene por compatibilidad con versiones anteriores, la creación de un objeto MouseEvent debe realizarse utilizando el MouseEvent()constructor.

var evt = new MouseEvent("click", {
    view: window,
    bubbles: true,
    cancelable: true,
    clientX: 20,
    /* whatever properties you want to give it */
});
targetElement.dispatchEvent(evt);

Demostración: http://jsfiddle.net/DerekL/932wyok6/

Esto funciona en todos los navegadores modernos. Para navegadores antiguos, incluido IE, MouseEvent.initMouseEventlamentablemente deberá usarse, aunque está en desuso.

var evt = document.createEvent("MouseEvents");
evt.initMouseEvent("click", canBubble, cancelable, view,
                   detail, screenX, screenY, clientX, clientY,
                   ctrlKey, altKey, shiftKey, metaKey,
                   button, relatedTarget);
targetElement.dispatchEvent(evt);
Derek 朕會功夫 avatar Jan 04 '2015 00:01 Derek 朕會功夫