What are inline event handlers, and why is it best practice to use addEventListener() instead?

In the previous lecture videos, you learned how to work with events by using the addEventListener() method. But there is another, not recommended way, to work with events in JavaScript.

Inline event handlers are special attributes on an HTML element that are used to execute JavaScript code when an event occurs.

Here is an example of a button element with an inline click event handler:

<button onclick="alert('Hello World!')">Show alert</button>

When the user clicks on the button, the alert function is called and an alert dialog is displayed with the message Hello World!.

Another way to use inline event handlers is to call a function that is defined in a script tag in the HTML document.

Here is an example of defining a function called changeBgColor and calling it from an inline click event handler:

<script>
  function changeBgColor() {
    document.body.style.backgroundColor = "lightblue";
  }
</script>
 
<button onclick="changeBgColor()">Change background color</button>

When the user clicks on the button, the changeBgColor function is called and the background color of the page is changed to light blue. While it is possible to use inline event handlers like this, it is not considered a best practice.

For one reason, inline event handlers can only be used to attach one event listener to an element. If you want to attach multiple event listeners to the same element, you will need to use addEventListener(). Another reason is that inline event handlers mix HTML and JavaScript code together, which can make your code harder to read and maintain. It is better to keep your HTML code and JavaScript code separate by using addEventListener() to attach event listeners to elements.

Inline event handlers are not recommended for use in modern JavaScript. So, it is best practice to stick with the addEventListener() method when working with events in JavaScript.