user541597
user541597

Reputation: 4345

javascript function needs doubleclick to work

I have these two javascript functions that for some reason I have to click the button twice for them to work. any ideas?

var shirts = new Array("shirtpink.png","shirtred.png", "shirtblue.png", "shirtyellow.png","shirt.png");

var index = 0;
function changecolor(){
    if (index > 4){
        index = 0;
    }
    var shirtpick = document.getElementById("shirt");
    shirtpick.setAttribute('src',shirts[index]);
    index++;
}

other function:

function changecolorback(){
    index--;
    i++;
    if (index < 0){
        index = 4;
    }
    var shirtback = document.getElementById("shirt");
    shirtback.setAttribute('src',shirts[index]);
}

Upvotes: 0

Views: 162

Answers (2)

davin
davin

Reputation: 45545

var shirts = ["shirtpink.png","shirtred.png", "shirtblue.png", "shirtyellow.png","shirt.png"],
    index = 0;

function changecolor(amount){
   index = (index + amount) % shirts.length;
   document.getElementById("shirt").setAttribute('src',shirts[index]);
}

The reason was your increments: You were incrementing after your code executed (in one function, but not in the other, so your changecolorback() should have behaved ok).

You also had i++ which looked redundant, and some variables that were only used once.

I shortened your code (drastically) so you get to these comments without too much scrolling. Instead of calling changecolorback(), you can now just do changecolor(-1), and the forward method is changecolor(1).

Another advantage is that this will allow you to jump by more than one, or a random amount, which might (or might not) be useful.

EDIT:

JS implements modulus like Java, so negatives still hold their sign. I.e. (-1)%5 === -1

You can overcome this pretty easily by changing (more elegant although not quite equivalent):

index = Math.abs(index + amount) % shirts.length;

or

index = ((index + amount) % shirts.length + shirts.length ) % shirts.length;

Upvotes: 5

Briguy37
Briguy37

Reputation: 8402

Try incrementing/decrementing index at the beginning of both functions. Also, you have 5 elements, not 4 in your array. You should probably use shirts.length to avoid this.

Upvotes: 0

Related Questions