I have challanged myself to build a carousel entirely with javascript but I'm not sure why my click events aren't working. When I click next or prev, the image should change.
Can anyone please tell me what im doing wrong?
let area = document.getElementById("area");
/* FIRST SLIDE */
let slide = document.createElement('div');
slide.setAttribute('class','slides');
area.appendChild(slide);
let image = document.createElement('img');
image.src = "image1.jpg";
slide.appendChild(image);
/* SECOND SLIDE */
let slide2 = document.createElement('div');
slide2.setAttribute('class','slides');
area.appendChild(slide2);
let image2 = document.createElement('img');
image2.src = "image2.jpg";
slide2.appendChild(image2);
//More slides can be added here
/* PREV */
let prev = document.createElement('a');
prev.innerHTML = "PREV";
prev.setAttribute('class', 'prev');
prev.addEventListener("click", function() {
showSlides(slideIndex += -1);
});
area.appendChild(prev);
/* NEXT */
let next = document.createElement('a');
next.innerHTML = "NEXT";
next.setAttribute('class', 'next');
next.addEventListener("click", function() {
showSlides(slideIndex += 1);
});
area.appendChild(next);
var slideIndex = 1;
showSlides(slideIndex);
function showSlides(n) {
console.log(n)
var i;
var slides = document.getElementsByClassName("slides");
console.log(slides.length)
if (n > slides.length) {slideIndex = 1} // goes back to the first one
if (n < 1) {slideIndex = slides.length} // goes to the last one
for (i = 0; i < slides.length; i++) {
slides[i].style.display = "none";
}
slides[slideIndex-1].style.display = "block";
}