skip to Main Content

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


  1. Chosen as BEST ANSWER

    Fixed it with this

    let index = 0
    
    let newSource = ()=>{
        if(filePath[index]==undefined){
            index = 0
        }
        let newPath = filePath[index]
        imgResultEl.src=newPath
    }
    
    let prevImg = () =>{
        index--
        newSource()
    }
    
    let nextImg = () =>{
        index++
        newSource()
    }
    prevBtnEl.addEventListener("click",prevImg)
    nextBtnEl.addEventListener("click",nextImg)
    

  2. 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

    let index = 0;
    const navigateImg = (direction) => {
        index += direction;
        // Clamp index
        if (index < 0) index = 0;
        else if (index >= filePath.length) index = filePath.length - 1; // unless you want to wrap
        // Set the image source
        imgResultEl.src = filePath[index];
        // Update the button status
        prevBtnEl.disabled = index === 0;
        nextBtnEl.disabled = index >= filePath.length - 1;
    };
    
    // Initial button status
    navigateImg(0);
    prevBtnEl.addEventListener("click", () => navigateImg(-1));
    nextBtnEl.addEventListener("click", () => navigateImg(1));
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search