Using addEventListener or the predefined eventsl like onclick, onload etc

Hi,

I have been reading and practicing Javascript for the last month and so far I’m happy with it. I noticed that you can add Event Listeners and trigger a function based on that event but I also noticed that you could add an event directly to any element as an attribute, something like…

<p  onclick="doSomething()">Click Me</p>
function doSomething(){
//do something 
}

So my question is why would someone add and event listener instead of adding that event directly in the element (as the sample above)?

The reason I’m asking is because adding event listeners involves more code…

var elementName= document.getElementById('elemenstsID');
elementName.addEventListener(&#8220;click&#8221;, doSomething, false);

I guess what I don’t know understand is why would someone choose to add an event listener instead, I know it is more OOP but doesn’t the “onclick”,“onload” etc do the same thing?

Sorry if my question doesn’t make any sense.

Thanks

I think code is cleaner when you separate events from html.

Also assigning events in javascript prevents situations when event gets fired before your script finished setting up variables and stuff, so you can first setup all stuff (load images, create variables, make sure whole page is loaded, etc…) and then assign events.

Thanks for your reply! Make sense.

A listener also allows you to attach additional code to an event without affecting whatever might already be attached.

Thanks a lot!