feat(curriculum): Add interactive examples to DOMContentLoaded lesson (#63464)

This commit is contained in:
Giftea ☕ 2025-11-03 20:30:54 +01:00 committed by GitHub
parent 4e57c5d13a
commit f3583d7038
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194

View File

@ -5,7 +5,7 @@ challengeType: 19
dashedName: what-is-the-domcontentloaded-event-and-how-does-it-work
---
# --description--
# --interactive--
The `DOMContentLoaded` event is fired when everything in the HTML document has been loaded and parsed. If you have external stylesheets, or images, the `DOMContentLoaded` event will not wait for those to be loaded. It will only wait for the HTML to be loaded.
@ -21,7 +21,9 @@ document.addEventListener("DOMContentLoaded", function () {
Once the DOM is loaded, the function will be executed and the message `DOM is loaded.` will be logged to the console.
Now, let's take a look at another example using the `DOMContentLoaded` event. In this example, we have an image inside the HTML:
Now, let's take a look at another example using the `DOMContentLoaded` event. In this example, we have an image inside the HTML. To update the image, we can create a function that changes the `src` and `alt` attributes for the image:
:::interactive_editor
```html
<h1>Image Change on DOM Loaded</h1>
@ -30,19 +32,24 @@ Now, let's take a look at another example using the `DOMContentLoaded` event. In
src="https://cdn.freecodecamp.org/curriculum/cat-photo-app/relaxing-cat.jpg"
alt="Cat relaxing"
/>
```
To update the image, we can create a function that changes the `src` attribute of the image:
<script src="index.js"></script>
```
```js
function changeImg() {
const img = document.getElementById("example-img");
img.src =
"https://cdn.freecodecamp.org/curriculum/responsive-web-design-principles/FCCStickers-CamperBot200x200.jpg";
img.alt = "CamperBot sticker";
console.log("image was just changed");
}
changeImg();
```
:::
We can then check if the DOM is still loading and add an event listener for the `DOMContentLoaded` event. If the `DOMContentLoaded` event has already fired, we can call the `changeImg` function directly:
```js