I was working on a personal project of making a slider using pure javascript. But The js code is not working. When I click the next button, the console shows an error that Uncaught TypeError: Cannot read property 'classList' of undefined. Same with the Previous button. I tried everything I could but I am not able to find the answer. =
JS Code:
var next1 = document.getElementById("next");
var prev1 = document.getElementById("prev");
var ulist = document.getElementsByTagName("ul").lastChild;
var ulist1 = document.getElementsByTagName("ul").firstChild;
var slides = document.querySelectorAll("li");
var active = document.getElementsByClassName("active")[0];
for(var i=0; i<3; i++){
slides[i].style.display = 'none';
}
slides[0].classList.add("active");
document.getElementsByClassName("active")[0].style.display = "block";
function next() {
active.classList.add("oldActive");
active.classList.remove("active");
if(Object.is(document.getElementsByClassName("oldActive")[0]) , ulist){
slides[0].classList.add("active");
}
else{
document.getElementsByClassName("oldActive")[0].nextElementSibling.classList.add("active");
}
}
function prev() {
document.getElementsByClassName("active")[0].classList.add("oldActive");
document.getElementsByClassName("active")[0].classList.remove("active");
if(Object.is(document.getElementsByClassName("oldActive")[0]) , ulist1){
slides[2].classList.add("active");
}
else{
document.getElementsByClassName("oldActive")[0].previousElementSibling.classList.add("active");
}
}
next1.addEventListener('click' , function() {
next();
});
prev1.addEventListener('click' , function() {
prev();
});
HTML Code:
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Image/Content Slider with Pure JS</title>
<link rel="stylesheet" href="css/style.css">
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.0.13/css/all.css" integrity="sha384-DNOHZ68U8hZfKXOrtjWvjxusGo9WQnrNx2sqG0tfsghAvtVlRW3tvkXWZh58N9jp" crossorigin="anonymous">
</head>
<body>
<header>
<h1>A Responsive Image/Content Slider</h1>
<p>It is made with HTML5, CSS3 and JavaScript</p>
</header>
<div class="left">
<h1><i class="fas fa-arrow-left" id="prev"></i></h1>
</div>
<main>
<div class="slider">
<ul class="slides" id="slidelist">
<li class="slide 1" name="slideo"><img src="images/hero_bg.jpeg" alt=""></li>
<li class="slide 2" name="slideo"><img src="images/hero_bg1.jpeg" alt=""></li>
<li class="slide 3" name="slideo"><img src="images/hero_bg1.jpeg" alt=""></li>
</ul>
</div>
</main>
<div class="right">
<h1><i class="fas fa-arrow-right" id="next"></i></h1>
</div>
<script type="text/javascript" src="js/main.js"></script>
</body>
</html>