skip to Main Content

I want the image to change every time I click the img. But the click to change img only works once. What have I done wrong?
The random image picker is from this website: https://picsum.photos/ and every time I click the link a new img appears.

const img = document.createElement("img");

img.src = "https://cdn.pixabay.com/photo/2024/02/05/03/10/sun-8553511_1280.jpg";
img.style.width = "300px";

document.body.appendChild(img);

img.addEventListener("click", function() {
  img.src = "https://picsum.photos/200/300";
});

2

Answers


  1. It would appear that subsequent requests to https://picsum.photos/200/300 do indeed return random images. However, the code isn’t telling the browser to make those requests because the code isn’t technically updating the src value to anything new.

    If you append a random value to the query string then it becomes a new URL and the browser makes a new request. For example:

    const img = document.createElement("img");
    
    img.src = "https://cdn.pixabay.com/photo/2024/02/05/03/10/sun-8553511_1280.jpg";
    img.style.width = "300px";
    
    document.body.appendChild(img);
    
    img.addEventListener("click", function() {
      img.src = "https://picsum.photos/200/300?" + Math.random();
    });
    Login or Signup to reply.
  2. The problem in your code is that you’re setting the src attribute to a static URL when the image is clicked. This URL doesn’t change on subsequent clicks, which is why the image only changes once. If we add a random string to the url, it work correctly.

    const img = document.createElement("img");
    
    img.src = "https://cdn.pixabay.com/photo/2024/02/05/03/10/sun-8553511_1280.jpg";
    img.style.width = "300px";
    
    document.body.appendChild(img);
    
    img.addEventListener("click", function() {
        // Add a random parameter to force a new image on each click
        img.src = "https://picsum.photos/200/300?" + Math.random();
    });
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search