event on property or use addeventlistener

Asked

Viewed 1,097 times

2

One thing I’ve always wondered if it’s standard to use addEventListener or the property of the tag <body onload="">. Some say it’s the addEventListener and others say it’s for property. Someone has an OFFICIAL answer?

I would also like to know why the addEventListener sometimes activates the event 4 times for no reason. It seems to me totally bugged and still doesn’t even work in old Internet Explorer. Why should I wear such a thing?

1 answer

6


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

It is true that Internet Explorer had serious bugs and did not support, for a long time, addEventListener. These times are past.

The rule I see among programmers is similar in Javascript and CSS. Just as it is not good practice to have CSS inline also should separate Javascript from HTML. The correct method is to use addEventListener, i.e., 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
    }
}

Browser other questions tagged

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