javascriptarraysimage-slider

Image is not showing in javascript image slider


I had created an image slider using HTML & JavaScript. The images are showing and working well when I use the slider with window.setInterval property and also with my next button but when I press my back button , the images are not found after the first image is shown. This means when I hit previous button the images are appearing in descending order one by one, but after first picture the Javascript function is unable to loop images from last picture to the first picture. Inspecting the page following error is shown undefined:1

   Failed to load resource: net::ERR_FILE_NOT_FOUND

Please Help!

following is my Javascript code

arr=["SMSlogo.jpg","spiderlogo.jpg","yt.jpg"];
        var value=0;
        slide();
        function slide(){
            document.getElementById("pic").src=arr[value];  
            value++;
            if(value==arr.length){
                value=0;
            }
        }
        window.setInterval(slide,3000);

        function back(){
            document.getElementById("pic").src=arr[value];
            value--;
            if(value==0){
                value=arr[arr.length-1];
            }
        }
        function next(){
            document.getElementById("pic").src=arr[value];
            value++;
            if(value==arr.length){
                value=0;
            }
        }

I'm expecting that my back button work properly and all images should be visible when I click the back button.


Solution

  • It doesn't really make sense to do value = array.length -1 because the value = 2 is a valid index but it will get reset. The problem here is that the back function will reset value to two if it's equal to zero while it's a valid index and won't reset it when it's equal to -1, an invalid index.

    Basically replace the if(value == 0) to if(value < 0)