How can I dynamically change the image src in JavaScript and only display it after it’s fully loaded using javascript load image logic?

To just add on what @vindhya.rddy said there is another effective approach is to dynamically update the <img> tag’s onload handler when changing the image source.

This allows you to show a loader while the new image is loading:

function updateImageSrc(newSrc) {
  const image = document.getElementById("id1");
  const loader = document.getElementById("loader");

  loader.style.display = "block";
  image.style.display = "none";

  image.onload = function () {
    loader.style.display = "none";
    image.style.display = "block";
  };

  image.src = newSrc;
}

This method is clean and efficient; it reuses the same image element and dynamically attaches an onload handler to handle loading behavior every time the source changes.

Great for smooth UI transitions! Happy to help :slight_smile: