Reputation: 27
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="" class="main-hobby">
<div>
<img class="image1" src="./Assets/slider-1.png" alt="person-learning-new-technology">
<img class="image2" src="./Assets/slider-2.png" alt="a-house">
<img class="image3" src="./Assets/slider-3.png" alt="person-playing-golf">
<img class="image4" 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
Upvotes: 1
Views: 73
Reputation: 17566
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="" class="main-hobby">
<div>
<img class="image1" src="https://via.placeholder.com/200/green" alt="person-learning-new-technology">
<img class="image2" src="https://via.placeholder.com/200/gray" alt="a-house">
<img class="image3" src="https://via.placeholder.com/200/red" alt="person-playing-golf">
<img class="image4" src="https://via.placeholder.com/200/yellow" alt="xbox-controller">
</div>
Upvotes: 1
Reputation: 781340
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++;
}
}
Upvotes: 0