Trigger an event using pure JavaScript

1

I would like to know how to dispatch an event using JavaScript. I tried using the following code:

var atual = document.getElementById('teste');
atual.addEventListener('mouseover', function(){ alert('HUE HUE HUE BR') });
atual.dispatchEvent('mouseover');

But there is an error saying that the event does not exist:

  

Uncaught InvalidStateError: Failed to execute 'dispatchEvent' on 'EventTarget': The event provided is null.

JSFiddle .

    
asked by anonymous 22.08.2014 / 19:44

3 answers

1

Following the advice of colleague Wakim, I checked the documentation and found that the event is not created alone, ie it is necessary before you fire it creates it, it looks like this:

var atual = document.getElementById('teste');
atual.addEventListener('mouseover', function(){ alert('HUE HUE HUE BR') });
atual.dispatchEvent(new Event('mouseover'));

Flw

    
22.08.2014 / 19:55
1

I needed something like that, but for mousewheel a while ago and I made this code:

function createFakeMouseEvent(event, elemento) {

    var evt;
    if (!(window.mozInnerScreenX == null)) {
        // Firefox
        evt = document.createEvent("MouseEvents");
        evt.initMouseEvent(event, true, true, window, 120, 0, 0, 0, 0, 0, 0, 0, 0, 0, null);
        elemento.dispatchEvent(evt);
    } else {

        if ('onwheel' in document) {
            // Chrome, PhantomJS, Safari
            evt = document.createEvent("MouseEvents");
            evt.initMouseEvent(event, 0, 100, window, 0, 0, 0, 0, null, null, null, null);
            elemento.dispatchEvent(evt);
        } else if ( !! document.createEvent) {
            // IE9
            evt = document.createEvent("HTMLEvents");
            evt.initEvent(event, true, false);
            elemento.dispatchEvent(evt);
        } else if (document.documentMode == 9) {
            // IE10+, Safari
            var evt = document.createEvent("MouseEvents");
            evt.initEvent(event, true, true);
            elemento.dispatchEvent(evt);
        } else {
            // IE8
            var evt = document.createEventObject();
            elemento.fireEvent(event, evt);
        }
    }
}

The code got a bit complex because different browsers have different ways of firing events ... But it should work for what they want.

Demo: link

    
22.08.2014 / 19:56
0

An alternative that may be simpler is to make a layered architecture, which allows you to call your code directly without being through the event system.

function huehue(){
    alert('HUE HUE HUE BR')
}

// Agora o evento só delega para uma função pronta
var atual = document.getElementById('teste');
atual.addEventListener('mouseover', function(){ huehue() });

// E como huehue passou a ser uma função normal podemos chamá-la diretamente:
huehue();
    
22.08.2014 / 20:58