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.
JavaScript
x
10
10
1
$(function() {
2
var lis = $(".animated > .boxed"),
3
currentHighlight = 0;
4
5
N = 5;//interval in seconds
6
setInterval(function() {
7
currentHighlight = (currentHighlight + 1) % lis.length;
8
lis.removeClass('highlighted').eq(currentHighlight).addClass('highlighted');
9
}, 1000);
10
});
JavaScript
1
9
1
.boxed {
2
background-color: red;
3
padding:5px;
4
}
5
6
7
.highlighted {
8
background-color:blue;
9
}
JavaScript
1
15
15
1
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
2
<span class="animated">
3
<span class="boxed">1</span>
4
<span class="boxed">2</span>
5
<span class="boxed">3</span>
6
</span>
7
<p>
8
9
</p>
10
<span class="animated">
11
<span class="boxed">1</span>
12
<span class="boxed">2</span>
13
14
<span class="boxed">3</span>
15
</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:
JavaScript
1
21
21
1
$(function() {
2
const highlightClass = "highlighted";
3
4
$(".animated").each(function() {
5
var $container = $(this);
6
var $lis = $container.find(".boxed");
7
8
setInterval(function() {
9
var $highlighted = $container.find("." + highlightClass);
10
11
$highlighted.removeClass(highlightClass);
12
13
if ($highlighted.length == 0 || $highlighted.next().length == 0) {
14
$container.find(".boxed").first().addClass(highlightClass);
15
} else {
16
$highlighted.next().addClass(highlightClass);
17
}
18
}, 1000);
19
});
20
21
});
JavaScript
1
8
1
.boxed {
2
background-color: red;
3
padding: 5px;
4
}
5
6
.highlighted {
7
background-color: blue;
8
}
JavaScript
1
25
25
1
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
2
3
<p>
4
<span class="animated">
5
<span class="boxed">1</span>
6
<span class="boxed">2</span>
7
<span class="boxed">3</span>
8
</span>
9
</p>
10
<p>
11
<span class="animated">
12
<span class="boxed">1</span>
13
<span class="boxed">2</span>
14
15
<span class="boxed">3</span>
16
</span>
17
</p>
18
<p>
19
<span class="animated">
20
<span class="boxed">1</span>
21
<span class="boxed">2</span>
22
23
<span class="boxed">3</span>
24
</span>
25
</p>