How to split all code working together at the same time, with unlimited different classes and loop in animated class. Code is like this but i want to make it run at the same time, and put it with unlimited of animated class.
$(function() {
var lis = $(".animated > .boxed"),
currentHighlight = 0;
N = 5;//interval in seconds
setInterval(function() {
currentHighlight = (currentHighlight + 1) % lis.length;
lis.removeClass('highlighted').eq(currentHighlight).addClass('highlighted');
}, 1000);
});.boxed {
background-color: red;
padding:5px;
}
.highlighted {
background-color:blue;
}<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<span class="animated">
<span class="boxed">1</span>
<span class="boxed">2</span>
<span class="boxed">3</span>
</span>
<p>
</p>
<span class="animated">
<span class="boxed">1</span>
<span class="boxed">2</span>
<span class="boxed">3</span>
</span>Advertisement
Answer
There are number of ways for doing this but basically you need to handle each of the “animated”-containers separately. Now you are looping through all the “boxed”-elements on the page which is not what you want if I understood you correctly. Loop the “boxed”-elements inside each “animated”-container:
$(function() {
const highlightClass = "highlighted";
$(".animated").each(function() {
var $container = $(this);
var $lis = $container.find(".boxed");
setInterval(function() {
var $highlighted = $container.find("." + highlightClass);
$highlighted.removeClass(highlightClass);
if ($highlighted.length == 0 || $highlighted.next().length == 0) {
$container.find(".boxed").first().addClass(highlightClass);
} else {
$highlighted.next().addClass(highlightClass);
}
}, 1000);
});
});.boxed {
background-color: red;
padding: 5px;
}
.highlighted {
background-color: blue;
}<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<p>
<span class="animated">
<span class="boxed">1</span>
<span class="boxed">2</span>
<span class="boxed">3</span>
</span>
</p>
<p>
<span class="animated">
<span class="boxed">1</span>
<span class="boxed">2</span>
<span class="boxed">3</span>
</span>
</p>
<p>
<span class="animated">
<span class="boxed">1</span>
<span class="boxed">2</span>
<span class="boxed">3</span>
</span>
</p>