Functionally, I believe there is no difference between the two methods, either, will perform the function fn()
once this element is clicked. The differences between the two types, maybe it is more in terms of limitations than mode of operation.
<p onclick="fn()">click</p>
addEventListener('click', fn());
document.getElementById().onclick = fn();
Perhaps you should know that this way of dealing with events was standardized by Netscape still in the DOM Level 0, so that they could perform events Javascript, and was subsequently adopted by the most varied browsers. Only from the DOM Level 2 new methods have been introduced, such as addEventListener
.
The main differences with the traditional method (onclick="..."), are that multiple event handlers can be registered for the same event, greater control over when the event is triggered, and works with any DOM element.
A common misconception with the online model is belief
that it allows the registration of event handlers with
custom arguments. «1»
Since what really happens is that the browser’s Javascript engine creates an anonymous function containing the existing statements in the onclick attribute.
Another fact to consider is perhaps the portability they present. For example, if we want to change the name of a function linked to a button click event, we would have to make the changes directly in the code HTML. Among these there are several other particularities for each, and both have advantages and disadvantages in specific cases.
There are currently some compatibility problems for some of the standards imposed by W3C (DOM Level 3) and IE8, so some of the methods may not work in certain browsers.
Some References:
In the second and third line of code
fn
instead offn()
– Guilherme Bernal
@Guilhermebernal has been some time since I answered the question, and your suggestion is also very old, but in any case I will answer, I wrote
fn()
to symbolize a function, the same could befunction(callack){}
or simply interpretfn()
as a function defined above, the parentheses are indication of parameters in this my example.– Edilson