I'm working on including a CSS/HTML/JS-only image carousel into my site. However, using the below code, I can't get the carousel to initially display due to the initial display:hidden
aspect. The issue I'm running into is that if I only have the image denoted under img
in the CSS, I then end up applying those same styles to every other image on the page. I've tried using .image-box img
as the CSS selector, but as I mentioned, it seems to interfere with the display: hidden
property.
Any suggestions would be greatly appreciated!
CSS:
.carousel-container {
width: 500px;
padding: 0;
margin: 0 auto 4rem auto;
height: 350px;
}
.image-box {
width: 500px;
height: 350px;
}
.image-box img {
border-radius: 20px;
display: none;
}
.active {
display: block;
}
.indicators {
width: 250px;
margin: 20px auto 0 auto;
display: flex;
align-items: center;
justify-content: space-around;
}
.indicators button {
height: 10px;
outline: none;
cursor: pointer;
width: 10px;
border-radius: 100%;
border: 1px solid #c4c4c4;
background: none;
}
.indicators button:nth-child(1){
background-color: #c4c4c4;
}```
<br>
HTML
<body>
<div class="carousel-container">
<div class="image-box">
<img src="image1.png" id="carousel1" class="active">
<img src="image2.png" id="carousel2">
<img src="image3.png" id="carousel3">
</div>
<div class="indicators">
<button onclick = "dot(1)"></button>
<button onclick = "dot(2)"></button>
<button onclick = "dot(3)"></button>
</div>
</div>
</body>
JS:
const dots = document.querySelectorAll(".indicators button");
const images = document.querySelectorAll(".image-box img");
let i = 0;
let j = 3;
function indicator(num){
dots.forEach(function(dot){
dot.style.backgroundColor = "transparent";
});
document.querySelector(".indicators button:nth-child(" + num + ")").style.backgroundColor = "#c4c4c4";
}
function dot(index){
images.forEach(function(image){
image.classList.remove("active");
});
document.getElementById("carousel" + index).classList.add("active");
i = index - 1;
indicator(index);
}