Home > Net >  javascript image swapper is showing a box instead of my images
javascript image swapper is showing a box instead of my images

Time:01-26

I'm getting a issue where none of my images can be seen, just a box. i've got 4 images that i want to swap every 2 seconds

<picture>
    <img src="" alt="" >
    <div>
        <img  src="./Assets/slider-1.png" alt="person-learning-new-technology">
        <img  src="./Assets/slider-2.png" alt="a-house">
        <img  src="./Assets/slider-3.png" alt="person-playing-golf">
        <img  src="./Assets/slider-4.png" alt="xbox-controller">
    </div>
</picture>

Here's my javascript, i'm new to this so im not sure what is going on.

const image1 = document.querySelector('.image1')
const image2 = document.querySelector('.image2')
const image3 = document.querySelector('.image3')
const image4 = document.querySelector('.image4')
const images = [image1, image2, image3, image4];
let index = 0;

const mainHobby = document.querySelector('.main-hobby');

console.log(images);

function change() {
    mainHobby.src = images[index]
    index > 2 ? index = 0 : index   ;
    ;
}

window.onload = function () {
    setInterval (change, 2000);
}

and css if needed

.main-hobby {
     display: block;
     width: 70px;
     height: 70px;
     margin-bottom: 20%;
   }

thanks for any help you can give

this is what i see

CodePudding user response:

You're trying to set the src to an image element, you should be setting it to the image's src:

function change() {
    mainHobby.src = images[index].src;
    if (index >= images.length-1) {
        index = 0;
    } else {
        index  ;
    }
}

CodePudding user response:

You have to set only the src attribute and not the entire img tag inside to maon-hobby container. Like that:

const image1 = document.querySelector('.image1')
const image2 = document.querySelector('.image2')
const image3 = document.querySelector('.image3')
const image4 = document.querySelector('.image4')

const images = [image1, image2, image3, image4];
let index = 0;

const mainHobby = document.querySelector('.main-hobby');

// console.log(images);

function change() {
  console.log(index)
  let src = images[index].getAttribute('src');
  mainHobby.src = src
  console.log(mainHobby)
  index > 2 ? index = 0 : index   ;  
}

window.onload = function () {
   setInterval (change, 2000);
}
.main-hobby {
  display: block;
  width: 70px;
  height: 70px;
  margin-bottom: 20%;
}
<img src="https://via.placeholder.com/200/green" alt="" >

  <div>
    <img  src="https://via.placeholder.com/200/green" alt="person-learning-new-technology">
    <img  src="https://via.placeholder.com/200/gray" alt="a-house">
    <img  src="https://via.placeholder.com/200/red" alt="person-playing-golf">
    <img  src="https://via.placeholder.com/200/yellow" alt="xbox-controller">
  </div>

  •  Tags:  
  • Related