javascriptevent-handlinginline-code

onclick="" vs event handler


If I want a function to be executed, I prefer doing inline js:

<p id="element" onclick="doSomething();">Click me</p>

because it is easier to debug.

However, I hear people saying not to use inline js, and do:

document.getElementById('element').onclick = doSomething;

Why is the js event listener recommended?


Solution

  • Basically it has to do with the whole keep everything separate I believe. So keep HTML/CSS/JS all separate. It makes your HTML tidier and, I think, easier to navigate without.

    Then when/if you need to make large changes, you have ample space with having to shift the inline JS to an external file anyway OR if you want to apply the same function to more than one button, then it's less code. And less code is a happier place

    If you have your JS files properly, and thoroughly documented then navigating them by an outside person is made eaiser