+ 2

Slider not working Properly?

HTML ------------------------------------------------------------------ <div> <button id="prev">Prev</button> <img id="image" src="resources/images/1.jpg"> <button id="next">Next</button> </div> JS------------------------------------------------------------------ var images = ["resources/images/1.jpg", "resources/images/2.jpg", "resources/images/3.jpg"]; var slider = document.getElementById("image"); var next = document.getElementById("next"); var currentImage = 0; next.addEventListener("click", nextFunc); function nextFunc() { currentImage ++; if (currentImage >= images.length) { currentImage = 0; } else { slider.src = images[currentImage]; } }

5th Apr 2018, 11:20 AM
Mohamed Kalith
Mohamed Kalith - avatar
1 Odpowiedź
0
Hi Mohamed You need to use the window.onload function before you call get the document ids This means that some of you variables will need to pushed into the global scope (not best practice but fine when you are learning): working code ================================================= var currentImage = 0, next, images, slider; function nextFunc() { currentImage ++; if (currentImage >= images.length) { currentImage = 0; } else { slider.src = images[currentImage]; } } window.onload = function() { next = document.getElementById("next"); slider = document.getElementById("image"); images = ["resources/images/1.jpg", "resources/images/2.jpg", "resources/images/3.jpg"]; next.addEventListener("click", nextFunc); }
5th Apr 2018, 2:34 PM
Mike Choy
Mike Choy - avatar