feat(curriculum): Add interactive examples to inline event handler lesson (#63467)

This commit is contained in:
Giftea ☕
2025-11-03 20:41:18 +01:00
committed by GitHub
parent 8be088c1f3
commit d242cc9c22

View File

@@ -5,7 +5,7 @@ challengeType: 19
dashedName: what-are-inline-event-handlers-and-why-is-it-best-practice-to-use-addeventlistener-instead
---
# --description--
# --interactive--
In the previous lessons, 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.
@@ -13,16 +13,22 @@ Inline event handlers are special attributes on an HTML element that are used to
Here is an example of a `button` element with an inline click event handler:
:::interactive_editor
```html
<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:
:::interactive_editor
```html
<script>
function changeBgColor() {
@@ -33,6 +39,8 @@ Here is an example of defining a function called `changeBgColor` and calling it
<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.