event on the property or use addEventListener

2

One thing I've always wanted to know, is whether to use addEventListener or the property of the <body onload=""> tag. Some say it's addEventListener and some say it's property. Does anyone have an OFFICIAL answer?

I'd also like to know why addEventListener sometimes activates the event 4 times for no reason at all. It seems to me totally bugged and still does not work in old Internet Explorer. Why am I going to use such a thing?

    
asked by anonymous 17.04.2015 / 18:57

1 answer

5

You can use both. They both do what is asked of them.

It's true that Internet Explorer had serious bugs and did not support addEventListener for a long time. These times are of the past.

The rule I see between programmers is similar in JavaScript and CSS. Just as it is not good practice to have inline CSS also separate JavaScript from HTML . The correct method is to use addEventListener , ie JavaScript outside of HTML.

Wrong because it makes it impossible to follow JavaScript within HTML:

<div onclick="if(a == 20){ chamarMinhaFuncao(this, 203); }else{ a = 25; chamarOutraFuncao(this, null); return false}">Clique aqui!</div>

Right, clean and separate from HTML:

var div = document.querySelector('div');
div.addEventListener('click', function(){ // ou div.onclick = function(){
    if (a == 20) {
        chamarMinhaFuncao(this, 203);
    } else {
        a = 25;
        chamarOutraFuncao(this, null);
        return false
    }
}
    
17.04.2015 / 22:54