views:

123

answers:

4

Why its recommended not use onclicks in your HTML.Use Event Handlers in your JS file is considered as best practice???

+7  A: 

You can only have one handler with on*.

But no limits on the number of handlers you can attach to the same element for the same event when using the event registration model.

Besides, it helps consolidate all behavior within Javascript and not sprinkled throughout the codebase.

Note: you can attach events using on* inside your Javascript as well. The DOM event registration model was introduced to fix this very problem. 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.

Instead, a better approach is to use the event registration. Continuing the above example (this is just for demonstration and it's 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".
Anurag
Do u think there is any case in which on* model is good/has/should be used/preferred over listener model ?
Anil Namde
If you're writing very simple sites with very few pages, and need it done quickly, then sure why not.
Anurag
+3  A: 

It separates your code from your content and markup. The cleaner that separation is, the easy it is to maintain, especially when your team is bigger than 1.

rikh
+2  A: 

Also, it contributes to the separation of concerns. HTML is the structure of your page, but Javascript is the "behavior". Separating the structure from the behavior allows more code reuse and ease of maintenance. (This is also why presentation [css] is separated from structure)

W_P
+1  A: 

It promotes a clean separation between design (HTML, CSS) and action (javascript). For much the same reason that its best to keep server side code separated from the display code.

jamone