Skip to main content
2 of 3
edited title, improved syntax highlighting
amon
  • 12.6k
  • 36
  • 67

Image Carousel in JavaScript

I created a very basic "image projector" that shows the current one and shows the next on clicking into the image.

And yeah, it works, but I don't think that's a very elegant way to do it. Any advice please?

Bear in mind I'm just starting my JavaScript classes and that's my third assignment, but the teacher is not really helpful when it comes to clean code, for him if it works, it works :/

Anyway, here's the full code: http://jsfiddle.net/AngelCJ/F5Hg7/

And the messy part:

/* loads the first image of the ul element using the n counter */
window.onload = function loadFirst() {
    var n=0;
    document.getElementById("list").children[n].style.display="block";
    /* onclick event, add +1 to the counter */
    document.getElementById("btn").onclick = function slider(){
        n++;
        /* and display the corresponding image */
        document.getElementById("list").children[n].style.display="block";
        /* while deleteing the previous one */
        document.getElementById("list").children[n-1].style.display="none";
        /* if we reach the final image */
        if(n==3) {
            /* shows the final image */
            document.getElementById("list").children[3].style.display="block";
            /* and after we click on it */
            document.getElementById("btn").onclick = function slider(){
                /* deletes it to leave the space to the first one */
                document.getElementById("list").children[3].style.display="none";
                /* returning to it loading the function to start again */
                loadFirst();
            }
            return;
        }
    }
}