peter k peter k - 3 months ago 7
Javascript Question

Using a switch inside of a function

var slideIndex = 1;
showDivs(slideIndex);

function plusDivs(n) {
showDivs(slideIndex += n);
}

function showDivs(n){
var i;
var x = document.getElementsByClassName("banner").style;
if (n > 4) {slideIndex = 1}
if (n < 1) {slideIndex = 4}

switch (n) {
case '1': x.backgroundImage = "url('1.jpg')";
break;
case '2': x.backgroundImage = "url('2.png')";
break;
case '3': x.backgroundImage = "url('3.jpeg')";
break;
case '4': x.backgroundImage = "url('4.png')";
break;
}

}


This is my script.
What I want it to do, is when I press a button, it adds 1 or takes away 1 from the slideIndex, and depending on which slide index it's currently at I want to use the switch and then set the background image of the class "banner" to the image corresponding to the number. This doesn't seem to work however. What is wrong with it?

Answer

The reason it doesn't work is because n is a number but your switch cases are strings. Just remove the quotes around your cases.

function showDivs(n){
    // ...

    switch (n) {
        case 1: // ...
        case 2: // ...
        case 3: // ...
        case 4: // ...
    }
}   

Since your image names correspond to the value of n, another improvement you can make is to use n directly instead of going through the switch:

function showDivs(n){

    // ...

    var extension = n % 2 === 0 ? '.jpg' : '.png';
    x.backgroundImage = "url('" + n + extension +"')";
}

Note: You have two JPEG images with different extensions, you might consider renaming them to a consistent extension to simplify your use case. Otherwise you might want to stick to the switch statement.


As mentioned by CoderGLM in the comments, document.getElementsByClassName("banner") will return a node list of all elements with the class banner. This means you need to extract a certain element, probably the first one:

x = document.getElementsByClassName("banner")[0].style;
Comments