Christopher Sarka
Christopher Sarka

Reputation: 13

Using a loop to preform actions on an array, that is being used as a selector

My thought is that it would be something like this:

var ads = newArray[];

ads[0] = "#classes";
ads[1] = "#fluke";
ads[2] = "#pelican";

for (i = 0, i <= 2, i++) {
    $(ads[i]).delay(1500).show();
}

It's a really rough idea of what I'm looking at doing. Eventually, I'm looking to make it scroll through ads for the site. Somehow, I'm tripping up on the logic of it. As it is, I would expect this code to delay 1500, then show ALL the divs. The ultimate goal is to show them one after another.

Upvotes: 0

Views: 50

Answers (2)

Christopher Sarka
Christopher Sarka

Reputation: 13

$(document).ready(function() {
var loopStart = '0';
var loopEnd = '3';
$('#class').css({display: 'inline-block'});
function adLoop() {
        setTimeout(function() {
            if (loopStart+1 == 1 && loopStart+2 == 2) {
                $('#fluke').css({display: 'none'});
                $('#pelican').css({display: 'none'});
                $('#class').css({display: 'inline-block'});
            }
            if (loopStart+1 == 2 && loopStart+2 == 3) {
                $('#class').css({display: 'none'});
                $('#pelican').css({display: 'none'});
                $('#fluke').css({display: 'inline-block'});
            }
            if (loopStart+1 == 3 && loopStart+2 == 4) {
                $('#class').css({display: 'none'});
                $('#fluke').css({display: 'none'});
                $('#pelican').css({display: 'inline-block'});
            }
            if (loopStart+1 == 4 && loopStart+2 == 5) {
                $('#fluke').css({display: 'none'});
                $('#pelican').css({display: 'none'});
                $('#class').css({display: 'inline-block'});
                loopStart = 0;
            }
            loopStart++;
            if (loopStart <= loopEnd) {
                adLoop();
            }
        }, 5000)
}
adLoop();
})

This is what I've come up with. I'd like to do the same thing with an array.

Upvotes: 0

Jason McCreary
Jason McCreary

Reputation: 73031

From the docs of delay():

Only subsequent events in a queue are delayed; for example this will not delay the no-arguments forms of .show() or .hide() which do not use the effects queue.

The following should get around this as it triggers the effects queue. Adjust the argument for show() to your liking.

$('#target1').delay(1500).show('fast');

See the fiddle.

As an aside, there's no reason to build an array. You can select multiple elements at once:

$('#target1, #target2').show();

See another fiddle.

Upvotes: 1

Related Questions