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";
4});

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 🤷‍♂️

Outline

Go Pro?

If you upgraded to pro, sign in here

  • About
  • Blog
  • Privacy
Looking to email me? You can get me on my first name at allthecode.co