Why its recommended not to use onclicks in HTML.Use event handlers in your JS file

Why its recommended not to use onclicks in HTML.Use event handlers in your JS file is considered best practice ???

+2


a source to share


4 answers


You can only have one handler with on*

.

But there is no limit to the number of handlers you can attach to the same element for the same event using the event registration model.

Plus, it helps to consolidate all the behavior in Javascript and not sprinkle the entire codebase.

Note. You can attach events using * inside your Javascript. To solve this problem, the DOM event registration model was introduced. See this example for more information:



// HTML
<p id="somePara" onclick="alert('First')">...</p>

// Javascript
var el = document.getElementById("somePara");

el.onclick = function() {
    alert("Second");
};

el.onclick = function() {
    alert("Third");
};

// when <p> is clicked, it alerts "Third", overwriting the first two handlers.

      

It is better to use event registration instead. Continuing with the above example (this is just for demonstration and it is not cross browser),

el.addEventListener("click", function() {
    alert("Un");
});


el.addEventListener("click", function() {
    alert("Dos");
});

// clicking on the <p> will now alert "Third", "Un", and "Dos".

      

+9


a source


Separates your code from your content and markup. The clearer this separation is, the easier it is to maintain it, especially when your team is larger than 1.



+3


a source


It also promotes separation of concerns. HTML is the structure of your page, but Javascript is the "behavior". Separating structure from behavior allows for more code reuse and ease of maintenance. (This is why presentation [css] is decoupled from structure)

+2


a source


This contributes to a clear separation between design (HTML, CSS) and action (javascript). For the same reason, it is best to keep the server-side code separate from the displayed code.

+1


a source







All Articles