Categories
JavaScript Answers

How to create a JavaScript callback for knowing when an image is loaded?

Spread the love

Sometimes, we want to create a JavaScript callback for knowing when an image is loaded.

In this article, we’ll look at how to create a JavaScript callback for knowing when an image is loaded.

How to create a JavaScript callback for knowing when an image is loaded?

To create a JavaScript callback for knowing when an image is loaded, we can use the onload method.

For instance, we write

const logo = document.getElementById("sologo");

logo.onload = () => {
  console.log("The image has loaded!");
};

logo.src = "https://picsum.photos/200/300";

to get the img element with getElementById.

Then we set logo.onload to a function that runs when the image is loaded.

Finally, we set logo.src to the image URL to load the image.

Conclusion

To create a JavaScript callback for knowing when an image is loaded, we can use the onload method.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *