Why its recommended not to use onclicks in HTML.Use event handlers in your JS file
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 to share