I have a carousel created on my own and I want to know how I can do that with JS. I know how I can do it by CSS but the problem is the change of the photos. Why change the src so that is my problem. If anyone knows how can I do it in JS it will be alright. Maybe changing the classes or something.
let imagenEnsaladas = document.getElementById("photosEnsaladas");
let buttonNext = document.getElementById("nextPhoto");
let carruselLi = document.getElementById("carruselLista").getElementsByTagName("li");
let positionCarrusel = 0;
let carruselPhotos = [
"assets/carrusel/ens.-ventresca-300-x300-300x300.png",
"assets/carrusel/ensalada bacalao200x200.png",
"assets/carrusel/ensalada-alcachofas-300x-300-300x300.jpg",
"assets/carrusel/ENsalada-yemas-300x300.png",
"assets/carrusel/ensalada-de-queso-cabra300x300-300x300.png",
];
window.onload = function playFoto() {
carruselLi[positionCarrusel].style.backgroundColor = "red";
if (positionCarrusel >= carruselPhotos.length) {
positionCarrusel++;
} else if (positionCarrusel > carruselPhotos.length) {}
imagenEnsaladas.src = carruselPhotos[positionCarrusel];
buttonNext.addEventListener("click", clickNextFoto);
function clickNextFoto() {
if (positionCarrusel >= carruselPhotos.length - 1) {
positionCarrusel = 0;
} else {
positionCarrusel++;
console.log(positionCarrusel);
}
imagenEnsaladas.src = carruselPhotos[positionCarrusel];
for (let i = 0; i < carruselLi.length; i++) {
if (i === positionCarrusel) {
carruselLi[positionCarrusel].style.backgroundColor = "red";
} else {
carruselLi[i].style.backgroundColor = "#1a1d20";
}
}
}
};
.textoNovedades {
margin: 0% 5% 0% 5%;
line-height: 30px;
}
.tablaNovedadesEnsalada {
display: flex;
flex-direction: row-reverse;
background: #1a1d20;
color: rgb(246, 225, 185);
justify-content: center;
align-items: center;
padding: 2% 2% 2% 2%;
width: 100%;
}
.carruselEnsaladas {
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
}
.nextPhoto {
background-image: url(assets/carrusel/siguiente.jpg);
background-size: auto;
background-position-x: 54%;
border-radius: 12px;
background-position-y: 47%;
width: 60%;
height: 9vh;
margin: 7%;
border: 3px;
box-shadow: 3px 3px 3px #999;
}
.tablaNovedadesEnsalada ul {
list-style: none;
}
<section class="tablaNovedadesEnsalada">
<div class="carruselEnsaladas">
<img src="" alt="photos carrusel" id="photosEnsaladas" class="photosEnsaladas">
<button id="nextPhoto" class="nextPhoto">
</button>
</div>
<p class="textoNovedades">
<ul id="carruselLista">
<li value="0"> ensalada de laminas de bacalao</li>
<li value="1"> Ensalada de alcachofas</li>
<li value="2"> Ensalada de yemas</li>
<li value="3">ensalada de ventresca</li>
<li value="4">Ensalada queso cabra</li>
</ul>
</p>
</section>