Sham
Sham

Reputation: 414

Using the for-loop effectively

In my webpage, I have to animate a different number of images per tab. In one tab, I have to animate three images. In another, I have twenty images to animate.

Presently, I am using two for-loops to handle this. I know it's a silly way of handling it; is there a better way to do this?

Here is my code:

function nextimageelev() {
    var elevcounter = 0;
    for (i = 0; i < 3; i++) {
        if (elevcounter == i) {
            $("#" + i).fadeIn();
        }
        else {
            $("#" + i).hide();
        }
    }
    if (elevcounter < 2) {
        elevcounter++;
    }
    else {
        elevcounter = 0;
    }
}

How do I make it more flexible to avoid hard-coding the conditional part? Currently, I have to write two for-loops to handle two animations.

Upvotes: 0

Views: 66

Answers (1)

Mike Brant
Mike Brant

Reputation: 71384

Why not simply add a common class to the elements you want to animate so you can use that as your selector:

$('.someClass').fadeIn();

Upvotes: 2

Related Questions