How do you change the src value of image using JavaScript?

I’ve created a div with the class ‘avatar-container’ inside which there’s an image tag. Here’s the code:

<div class="avatar-container">
    <img src="assets/avatar/avatar-1.jpg"  alt="Picture of a person">
</div>

Now I want to create a carousel thing, that will change the avatar image every 1 second. The images are present locally and I’ve created an array to hold the relative URL to all the images. I’m calling a function at 1 second interval using the setInterval function, and inside that function I want to change the src value to the next item in the array.

I’ve set the logic to continue looping through the array, and read the data correctly. Here’s the code to get the avatar container and the image tag inside it.

const imageContainer = document.querySelector('.avatar-container')
const image = imageContainer.querySelector('img');

const setImage = (url) => {
    image.src = url //url is the relative path I'm reading from the array
}

I’m also using the window.onload function to make sure the function runs after everything is loaded, but still the image doesn’t change. I’ve tried to console.log the image div after I’ve set the new src value. The new value is shown in the src attribute but still the image doesn’t get changed.

How do I change the src value of image tag?

Where in your code are you calling setImage and passing it a new image?

So I’ve a function changeCarouselItem which is called at 1 second interval using setInterval function. Inside the changeCarouselItem I’m calling the setImage function and passing the url data to it

Here’s the entire code for reference -

const userData = [
  {
    designerName: "Linda Wilson",
    primary: "#CECDCE",
    accent: "#D9C68E",
    textColor: "#FFFFFF",
    avatar: "assets/avatar/avatar-1.jpg",
    image: "assets/images/furniture-1.jpg",
    imageDescription: "",
  },
  {
    designerName: "Michael Jones",
    primary: "#FFFFFF",
    accent: "#FFB664",
    textColor: "#010001",
    avatar: "assets/avatar/avatar-2.jpg",
    image: "assets/images/furniture-2.jpg",
    imageDescription: "",
  },
  {
    designerName: "Thomas Davis",
    primary: "#CFCECF",
    accent: "#BBD49B",
    textColor: "#FFFFFF",
    avatar: "assets/avatar/avatar-3.jpg",
    image: "assets/images/furniture-3.jpg",
    imageDescription: "",
  },
  {
    designerName: "Patricia Jones",
    primary: "#B5B8C3",
    accent: "#E0E5E7",
    textColor: "#FFFFFF",
    avatar: "assets/avatar/avatar-4.jpg",
    image: "assets/images/furniture-4.jpg",
    imageDescription: "",
  },
];

window.onload = (e) => {
  changeCarouselItem();
};

let index = 0;
const accentDiv = document.getElementById("accent-div");
const container = document.getElementById("container");
const nameHeader = document.querySelector(".designer-name");
const carouselCounter = document.querySelector(".carousel-counter");
const avatarContainer = document.querySelector('.avatar-container');
const pictureContainer = document.querySelector('.picture-container');

const changeCarouselItem = () => {
  const data = userData[index];
  setBackground(data?.primary, data?.accent);
  setDesignerName(data?.designerName, data?.textColor);
  setCarouselIndex(index, userData.length, data?.textColor);
  if (index === userData.length - 1) {
    index = 0;
  } else {
    index++;
  }
};

const setBackground = (primary, accent) => {
  container.style.backgroundColor = primary;
  accentDiv.style.backgroundColor = accent;
};

const setDesignerName = (name, color) => {
  name = name.replace(' ', '<br>');
  nameHeader.innerHTML = name;
  nameHeader.style.color = color;
};

const setCarouselIndex = (index, total, color) => {
  const currentItem = carouselCounter.querySelector('.current-item');
  const totalItems = carouselCounter.querySelector('.total-items');
  const line = carouselCounter.querySelector('.hr');
  currentItem.textContent = `0${index + 1}`;
  totalItems.textContent = `0${total}`;
  currentItem.style.color = color;
  totalItems.style.color = color;
  line.style.backgroundColor = color;
}

const setImage = (avatar, image) => {
  const avatarImage = avatarContainer.querySelector('img');
  avatarImage.src = avatar;
}
setInterval(changeCarouselItem, 2000);

Ignore the functions. It just sets text contents and background.

So we do not have to recreate the HTML to test your code, can you please at least supply it? Thanks.

Also, like I said before, I do not see where you are calling setImage in your code. If you do not call it and pass the applicable image sources as arguments, nothing will change.

1 Like

Sorry, forgot to update that bit. The setImage function is called from inside of changeCarouselItem function.

Here’s the HTML bit

<body>
    <div id="container" class="container">
      <div id="accent-div" class="accent-div"></div>
      <nav class="navigation">
        <div class="logo">
          <div class="circle"></div>
          <h4 class="company-name">Furniture</h4>
        </div>
        <ul class="nav">
          <li class="active">Designers</li>
          <li>History</li>
          <li>News</li>
        </ul>
        <ul class="nav">
          <li>Shop</li>
          <li>About</li>
        </ul>
        <div class="menu">
          <button>
            <object
              type="image/svg+xml"
              data="assets/menu.svg"
              class="menu-button"
            >
              Logo
            </object>
          </button>
        </div>
      </nav>
      <main class="main-section">
        <div class="designer-info">
          <h5>Designer Furniture</h5>
          <h1 class="designer-name"></h1>
          <div class="designer-avatar">
            <div class="avatar-container">
              <img src="assets/avatar/avatar-1.jpg"  alt="Picture of a person">
            </div>
            <div class="location">
              <h5>New York</h5>
              <h5>Furniture<br>Designer</h5>
            </div>
          </div>
        </div>
        <div class="furniture-carousel">
          <div class="picture-container">
            <img src="assets/images/furniture-1.jpg" alt="Picture of furniture">
          </div>
          <div class="carousel-counter">
            <span class="current-item"></span>
            <span class="hr"></span>
            <span class="total-items"></span>
          </div>
        </div>
      </main>
    </div>
  </body>

You’re going to need to learn how to debug your code sooner or later, I suggest you start now. In JavaScript Land, console.log() is your friend. Here’s the first check I would make:

const setImage = (avatar, image) => {
  const avatarImage = avatarContainer.querySelector('img');
  avatarImage.src = avatar;
  console.log({ avatar, image, avatarImage });
}
  • Add a log inside the setImage function and run your code.

  • Does nothing get logged to the console?
    Then you’re never reaching that code. Go up the chain and add a similar log to the function that should be calling setImage. Continue as needed.

  • Do unexpected values get logged to the console?
    Then maybe you need to adjust the inputs or your algorithm. Is avatar a string and a valid URL? Is avatarImg the correct HTMLElement?

Not in the code you posted above.

Yeah I was doing some debugging and during that I temporarily removed the code but forgot to revert back before posting here.

That’s a good idea to console.log(). Also as a note I’m using parcel-bundler and every time I console.log() the image element to check the src value, the relative path is omitted, there’s only the file name followed by a hypen and a string of random alphanumeric characters and then the file type

If the file path is assets/avatar/avatar-1.jpg the src value in console shows /avatar-1-1356abdd.jpg

Do you think maybe I’m missing some configuration in parcel bundler?

Does a 404 error show up in the console after you swap the image?