I have been trying to create a slideshow on one of the web pages I've been creating. I have created a div with a unique class name that is targeted in order to change the background image using JavaScript. So far, I have been able to do the following:
- Capture the div where I want to change the background image by using the querySelector
- Attempted to change the background image of said div using JavaScript
I have been debugging this function using DevTools, yet I cannot figure out why the image won't change. Any idea what is happening here? I have included snippets of the code below. Thank you.
HTML
<div class="content-one-right">
<div class="inner-content-one-right">
<div class="slideshow-container">
<a class="prev" onclick="transitionSlides(-1)">❮</a>
<a class="next" onclick="transitionSlides(1)">❯</a>
</div>
</div>
</div>
CSS
.content-one-right {
grid-column: col-start 7 / span 6;
height: 60vh;
}
.inner-content-one-right {
height: 90%;
width: 90%;
}
.slideshow-container {
height: 100%;
width: 100%;
display: flex;
justify-content: space-between;
align-items: center;
background-image: url('../images/home-slideshow/home1.jpg');
background-repeat: no-repeat;
background-size: cover;
}
.prev, .next {
cursor: pointer;
color: #FFF;
font-weight: bold;
font-size: 1em;
border-radius: 0 3px 3px 0;
}
.prev:hover, .next:hover {
background-color: rgba(0,0,0,0.8);
}
JavaScript
var slideshowIndex = 0;
function transitionSlides(n) {
var images = ["home1", "home2", "home3", "home4", "home5", "home6"];
slideshowIndex += n;
if(slideshowIndex < 0) {
slideshowIndex = images.length-1;
}
else if (slideshowIndex >= images.length) {
slideshowIndex = 0;
}
var getContainer = document.getElementsByClassName('slideshow-container')[0];
var imageToChange = "url('../images/home-slideshow/" + images[slideshowIndex] + ".jpg')";
getContainer.style.backgroundImage = imageToChange;
}