2

I've created this little fancy jQuery Snippet to toggle the class of an element in an interval:

setInterval(function(){$('.grid-item .slide-image').toggleClass('active')}, 800);

The script works fine! Now I got multiple elements with the base-class .slide-image in the wrapper .grid-item.

<div class="grid-item">
  <div class="slide-image"><img src="http://www.placehold.it/500x500/233953"></div>
  <div class="slide-image"><img src="http://www.placehold.it/500x500/03144b"></div>
  <div class="slide-image"><img src="http://www.placehold.it/500x500/030a4b"></div>
</div>

Is there a way to rewrite the snippet so the second .slide-image gets the class .active after the first one? Then the third element and so on...

The Problem: The amout of .slide-image-elements is no defined. In some cases there are two of them, in another there are four elements.

Check out my CodePen!

Pete
  • 57,112
  • 28
  • 117
  • 166
Jonas
  • 163
  • 1
  • 3
  • 10

2 Answers2

5

Try this

var slides = $('.grid-item .slide-image'),  // cache slides 
    counter = 0;                            // global counter

setInterval(function(){
  slides.removeClass('active');             // remove active class
  slides.eq(counter).addClass('active');    // add active class
  counter++;

  if (counter == slides.length) counter = 0;  // reset counter after last slide
}, 800);

Updated CodePen

Pete
  • 57,112
  • 28
  • 117
  • 166
  • Thanks! Works fine. Now I've added a Mouseover-Event and get the elements by `$(this).find(".slide-image")`. Now some weird stuff is happening: http://codepen.io/anon/pen/VmXNZj – Jonas Dec 06 '16 at 10:11
  • @Jonas this is a new question, but in short you need to clear your interval as each time you mouseover you are setting a new interval – Pete Dec 06 '16 at 10:13
1

You can check if current active element id last or not. if it is, then show first element in set else show next sibling element:

$(function(){
  var slides = $('.grid-item .slide-image');
  setInterval(function(){
    var currentactive = $('.active');
   var _target = currentactive.is(':last-child') ? slides.first() : currentactive.next();
   slides.removeClass('active')
  _target.addClass('active')
 }, 800);
});

Working Demo

Milind Anantwar
  • 81,290
  • 25
  • 94
  • 125