TIMEX
TIMEX

Reputation: 271604

How do I do a loop in JQuery?

<script>
  $(function() {
    $('#slideshow').crossSlide({
      sleep: 2,
      fade: 1
    }, [
      { src: 'picture1.jpg' },
      { src: 'picture2.jpg' },
    ])
  });
</script>

In this script, I apply a crossSlide effect to #slideshow. However, what if I have 20 divs, and I want to apply the crossSlide effect to each div with the class "slideshow"?

How do I loop through the divs, find the ones with the class .slideshow, and apply the respective image to each?

Edit: Each div has its own image that I want to show.

Upvotes: 1

Views: 173

Answers (2)

mpen
mpen

Reputation: 282805

$(function() {
    $('.slideshow').each(function(index,elem) {
        $(this).crossSlide({
            sleep: 2,
            fade: 1
        }, [
            { src: 'picture'+index+'A.jpg' },
            { src: 'picture'+index+'B.jpg' },
        ])
    });
});

You can make the image source filename a function of the current element. You might choose the filename based on the index, an attribute on that element, or something like that.

Otherwise, you have to write it out all 20 times if there's no pattern in your filenames.

Upvotes: 1

rahul
rahul

Reputation: 187020

Use a class selector combined with an element selector.

$('div.slideshow').crossSlide

Then you will have to use .each() on the elements and get the current object using $(this)

Upvotes: 6

Related Questions