30 Days Of JavaScript

Day 17: Events

Lesson 5: onload

onload allows us to wait until everything is ready before running some code, putting your script at the bottom of the HTML page is usually enough but it's not always viable to do that. Adding an event handler to the document to execute a block of code after the page has loaded is pretty bulletproof.

Let's make our ball turn green on load:

1window.addEventListener("load", (e) => {
2  console.log("Page loaded");
3  ball.style.backgroundColor = "blue";

Adding the event listened to document is unreliable so adding to window is the way to go thanks to event bubbling. If you console.log(e) in that function you will see that the target property is the document anyway so it won't fire until the document loads. You'll see that currentTarget is the window object. Another case where the element that fired the event isn't the same as where we attached the event listener.

Try changing window to document or even window.document - Strong chance the event won't fire for you 🤷‍♂️


Go Pro?

Upgrade to Pro for quizzes, tracked progress and a completion certificate for just $25 🚀

Want more developer tips, tricks and tools?
Then follow me:
FREE Coding Career Quick Start Guide 🚀
Discover the best way to learn to code, how to land a job and valuable resources to help your journey in this free 15 page value packed guide.
Looking to email me? You can get me on my first name at allthecode.co