Search code examples
jqueryfunctioncycleeach

Using jQuery's .each() function to attach a function to multiple slideshow containers


I have very many small jQuery Cycle slideshow divs (containers) on a one-page website like

    <div class="foo bar" data-value="1000"> // data-value varies on each container
        <img src="directory/img_0.jpg" alt="img 0" />
        <img src="directory/img_1.jpg" alt="img 1" />
        <img src="directory/img_2.jpg" alt="img 2" />
    </div>

and want to cycle them all - with each slideshow div having a different data-value - without hard coding/repeating

$(document).ready(function() {
  $('.foo.bar').cycle({
      speed: 300,
      timeout: 6000,
      delay: $('.foo.bar').data('value')
  });
});

for all occurences of such slideshow div. How can I "attach" or "bind" or "link" such jQuery function to each slideshow div so that each element's differing data-value is used? I suspect that jQuery's .each() function could allow me to do so - but how?

EDIT fiddle

Thank you very much in advance!


Solution

  • As you mention, .each() will let you do this quite easily:

    $('.foo.bar').each(function() {
        $(this).cycle({
          speed: 300,
          timeout: 6000,
          delay: $(this).data('value')
        });
    });
    

    Inside the .each callback, this refers to the element you are currently operating on.