Cyclability in jquery
-
There are three blocks with the class item. How to add a class every 3 seconds.
active
to the next element?I do it, but it doesn't work.
$(function() { $(document).each(function() { $(".item").removeClass("active"); $(".item.active").next().addClass("active"); }); });
-
Try this:
var params = { count: $(".item").length, now: 0 }
function set_active() {
if(params.now == params.count) {
params.now = 0;
}$(".item").removeClass("active");
$(".item[data-id="" + params.now + ""]").addClass("active");params.now++;
}set_active();
setInterval(set_active, 3000);
.active {
color: red;
}<script src="//code.jquery.com/jquery.min.js"></script>
<div class="item" data-id="0">Привет</div>
<div class="item" data-id="1">Привет</div>
<div class="item" data-id="2">Привет</div>