Functionally, I believe there is no difference between the two methods, either one or the other, will execute the fn()
function once this element is clicked. The differences between the two types may be more in terms of limitations than mode of operation.
<p onclick="fn()">click</p>
addEventListener('click', fn());
document.getElementById().onclick = fn();
Maybe you should know that this way of dealing with events was standardized by Netscape at DOM Level 0 so they could run Javascript events >, and was later adopted by the most varied browsers. Only new methods, such as addEventListener
, have been introduced since DOM Level 2
.
The main differences that exist with the traditional (onclick="...") method are that multiple event handlers can be registered for the same event, greater control over when the event is fired, and works with any DOM element.
A common misconception with the online model is the belief
that it allows the registration of event handlers with
custom arguments. «1»
What really happens is that the browser's JavaScript engine creates an anonymous function containing the existing declarations in the onclick attribute.
Another fact to consider is perhaps the portability they present. For example, if we want to rename a function bound to a click event of a button, we would have to make the changes directly in the HTML tag. Among these there are several other peculiarities for each, both of which have advantages and disadvantages in specific cases.
There are currently some compatibility issues 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: