Currently making a Site with HTML, CSS and JS in stackblitz.com and im trying to add an image slider into one of my pages. I've tried multiple methods online but the same issue happends, I input the code and the actual image slider works fine on it's respective page but the Index page won't load and instead displays this:
Error in /script.js (26:11) Cannot read properties of null (reading 'addEventListener')
Here is my code so far
Html
<body>
<div id="arrow-left" class="arrow"></div>
<div class="slide slide1"></div>
<div class="slide slide2"></div>
<div class="slide slide3"></div>
<div id="arrow-right" class="arrow"></div>
</body>
CSS
.slide {
margin: 0;
padding: 0;
font-family: Arial, Helvetica, sans-serif;
width: 100%;
height: 100vh;
overflow-x: hidden;
background-size: cover;
background-position: center;
background-repeat: no-repeat;
margin-left: 30%;
}
.slide1 {
background-image: url(
"https://media.geeksforgeeks.org/wp-content/uploads/20210812221217/pic1.png");
background-size: 350px 300px;
}
.slide2 {
background-image: url(
"https://media.geeksforgeeks.org/wp-content/uploads/20210812221254/pic2.png");
background-size: 350px 300px;
}
.slide3 {
background-image: url(
"https://media.geeksforgeeks.org/wp-content/uploads/20210812221322/pic3.png");
background-size: 350px 300px;
}
.arrow {
cursor: pointer;
position: absolute;
top: 54%;
margin-top: -35px;
width: 0;
height: 0;
border-style: solid;
}
#arrow-left {
border-width: 10px 15px 10px 0;
border-color: transparent #fff transparent transparent;
left: 67%;
margin-left: 20px;
}
#arrow-right {
border-width: 10px 0 10px 15px;
border-color: transparent transparent transparent #fff;
right: 7%;
margin-right: 20px;
top: 55%;
}
JS
let sliderImages = document.querySelectorAll(".slide"),
arrowLeft = document.querySelector("#arrow-left"),
arrowRight = document.querySelector("#arrow-right"),
current = 0;
function reset() {
for (let i = 0; i < sliderImages.length; i++) {
sliderImages[i].style.display = "none";
}
}
function startSlide() {
reset();
sliderImages[0].style.display = "block";
}
function slideLeft() {
reset();
sliderImages[current - 1].style.display = "block";
current--;
}
function slideRight() {
reset();
sliderImages[current + 1].style.display = "block";
current++;
}
arrowLeft.addEventListener("click", function () {
if (current === 0) {
current = sliderImages.length;
}
slideLeft();
});
arrowRight.addEventListener("click", function () {
if (current === sliderImages.length - 1) {
current = -1;
}
slideRight();
});
startSlide();
Sorry in advance if my code is really messy i've just been looking most of this stuff up as I go. How could I fix this? I suppose its a JS thing which is probably the part of this I know the least about.