I am trying to display image in HTML. With 2 functions where users can click next or previous image. The next button works until it reach the max array in filePath
and create an error. this is what the console provided net::ERR_FILE_NOT_FOUND
. And the previous button doesn’t work at all. I have tried looking into the solution in which mostly they use jQuery(I still haven’t learned about it and do not understand at all). Is there any other way to limit the next image button so that it doesn’t increment or decrement pass through the filePath
array?
Here is my code :
let filePath = ["img/frame/1.png", "img/frame/2.png", "img/frame/3.png", "img/frame/4.png", "img/frame/5.png", "img/frame/6.png", "img/frame/7.png", "img/frame/8.png", "img/frame/9.png"]
let imgResultEl = document.getElementById("img-result-el")
let prevBtnEl = document.getElementById("prev-btn-el")
let nextBtnEl = document.getElementById("next-btn-el")
let index = 0
let prevImg = () => {
if (index >= filePath.length && index <= 0) {
index--
let newPath = filePath[index]
imgResultEl.src = newPath
}
}
let nextImg = () => {
if (index <= filePath.length && index >= 0) {
index++
let newPath = filePath[index]
imgResultEl.src = newPath
}
}
prevBtnEl.addEventListener("click", prevImg)
nextBtnEl.addEventListener("click", nextImg)
2
Answers
Fixed it with this
See the comments for the obvious mistakes in your script
Here is a much simpler solution that is just using the length and direction
jQuery is not the answer here