Fire an event using pure Javascript

Asked

Viewed 4,201 times

2

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 then an error occurs saying that the event does not exist:

Uncaught Invalidstateerror: Failed to execute 'dispatchEvent' on 'Eventtarget': The Event provided is null.

Jsfiddle.

  • 1

    I recommend taking a look at the documentation of the method dispatchEvent, its parameter is an object Event not the event name. An example would be: dispatchEvent(new Event('mouseover'));

  • 1

    Valew man! I found out and actually I had to create the event, it was like this: var atual = document.getElementById('teste');

atual.addEventListener('mouseover', function(){ alert('HUE HUE HUE BR') });
atual.dispatchEvent(new Event('mouseover'));

3 answers

2

Following the advice of Mr Wakim, I checked the documentation and found that the event is not created alone, that is to say it is necessary before firing it create it, it was like this:

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

Flw

1

I needed something similar, but for mousewheel a while back 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 has become a bit complex because different browsers have different ways to trigger events... but it should work for whatever.

Demo: http://jsfiddle.net/vmvbb3hf/

  • Valew face for sure in the future can be useful but as the design and IE9+ the normal dispacht will serve.

1

An alternative that can be simpler is to build 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();
  • So Hugo the problem is usually when I link a function to a Liener I want to have access to target(this) so this solution is not used, but in another case it may be an option. Valew.

  • Ve can make huehuehue take the node as parameter: In Event you do huehue(this) and on the outside call you make huehue(atual)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.