javascript - Why its recommended not use onclicks in your HTML.Use Event Handlers in your JS file -


Why its recommended HTML does not use onclicks. Is using event handlers in your JS file as a best practice?

You can only have a handler with * .

But when using the Event Registration Model you can add the same element to the same event without any limitation on number of handler.

In addition, it helps to strengthen all the behavior within JavaScript, do not sprinkle in the codebase.

Note: You can also attach events by using * inside your javascript. Dome event registration model was introduced to fix this problem. See this example for more information:

  // HTML & lt; P id = "somePara" onclick = "warning ('first')" & gt; ... & lt; / P & gt; // javascript var l = document.getElementById ("some paragraph"); El.onclick = function () {warning ("second"); }; El.onclick = function ({warning ("third"); }; // when & lt; P & gt; This "third" warns, overwrites the first two handlers,  

Instead, using Event Registration is a better way. Continuing the above example (this is only for demonstration and it is not cross-browser),

  el.addEventListener ( "click", function () {alert ( "UN" );}); El.addEventListener ("click", function () {alert ("dos");}); // clicking & lt; P & gt; Now will warn "third", "un", and "dos".  

Comments