JavaScript Event Handling – Inline Event Handling vs External jQuery Event Handlers

htmljavascriptjquery

Working on a dynamic website that loads information from a JSON file and then populates the page with said elements.

My question has to do with event handling – as of now, I don't see any reason as to why I would need to add event handlers inline if I could just use the equivalent jQuery handler in an external script file. I could see the argument where one would say it allows for more control over events, but would that be true?

Here are the two methods I am looking at:

Inline:

<div class="family" onclick="goToFamilyPage()">This Family</div>

External/imported script:

$(document).on('click', '.family', function() {
    //do stuff
});

What would be the benifit of one of these versus the other?

Best Answer

It's better to use event handlers. Event handlers keep JavaScript out of your HTML which is usually better for decoupling reasons. The only time in-line JavaScript is okay is if you inject it via a template. This is often done when with React.js because it generates a lot of HTML (which is arguably a template).

Related Topic