Chris Chong
Chris Chong

Reputation: 187

add and remove class of each div

I want to know if there's any way to add class 'active' to each div by interval of time but only one of them can have the 'active' class on the inverval on jquery like:

<div class="item active"></div>
<div class="item"></div>
<div class="item"></div>

And after some interval of time

<div class="item"></div>
<div class="item active"></div>
<div class="item"></div>

Then later...

<div class="item"></div>
<div class="item"></div>
<div class="item active"></div>

I added something like this but is not what I want:

jQuery('.carousel-inner').mouseenter(function() {
  jQuery('.item').each(function(i) {
var $sh = jQuery(".item");
setInterval(function(){
    $sh.toggleClass("active");
}, 1000);
  });
});

Upvotes: 0

Views: 421

Answers (3)

War10ck
War10ck

Reputation: 12508

You'll need to use either setInterval or setTimeout recursively. I prefer setTimeout recursively simply because this guarrantees the previous operation has completed before the next one begins.

$(function () {
    
    var index = 1,
        max = $('.item').length;

    function setActive() {
        setTimeout(function () {
            $('.active').removeClass('active');
            index++;
            if(index > max) {
                index = 1;    
            }
            $('.item:nth-of-type(' + index + ')').addClass('active');
            setActive();
        }, 1500);
    }
    
    setActive();
    
});
div {
    width: 100px;
    height: 100px;
    margin-bottom: 10px;
    background: green;
}
div.active {
    background: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="item active"></div>
<div class="item"></div>
<div class="item"></div>

The previous code snippet is just an example. I'm not sure based on your post what the class does but the CSS should demonstrate the point of what you're trying to accomplish.

JSFiddle DEMO

Upvotes: 1

Balachandran
Balachandran

Reputation: 9637

try

var i=0;

setInterval(function(){

            $(".item.active").removeClass("active");  
            $(".item:eq("+i+")").addClass("active");
            i++;
            if(i>=$(".item").length){
               i=0;
            }

},100);

DEMO

Upvotes: 0

Doug
Doug

Reputation: 1

$('div.item').removeClass('active');
$('div.item:eq('+n+')' ).addClass('active');

where n would be the index of the item you want to add the active class to

Upvotes: 0

Related Questions