'How to transfer the existing class to the next order div and add a new class?
I have a question. I created a page with the following structure.
<div class="cover-header">
<span class="box-header checked">test1</span>
<span class="box-header">test2</span>
<span class="box-header">test3</span>
<span class="box-header">test4</span>
<span class="box-header">test5</span>
<span class="box-header">test6</span>
<span class="box-header">test7</span>
</div>
When I scroll through the page, a class named 'red' will be added to the box that had the 'checked' class, and I want the class named 'checked' to move on to the next box. (It will be deleted from the existing box) It's going to change like the code below.
<div class="cover-header">
<span class="box-header red">test1</span>
<span class="box-header checked">test2</span>
<span class="box-header">test3</span>
<span class="box-header">test4</span>
<span class="box-header">test5</span>
<span class="box-header">test6</span>
<span class="box-header">test7</span>
</div>
I tried 'next()' and 'after()', but it didn't apply. If I only use next(), the class will be added to all div... I want to be added only to the next div. So, used 'closest()' together, but it didn't apply.
$('.box-header.checked').next().closest().addClass('checked');
This should continue until the last div. As a result, if you scroll to the end, it will look like the code below.
<div class="cover-header">
<span class="box-header red">test1</span>
<span class="box-header red">test2</span>
<span class="box-header red">test3</span>
<span class="box-header red">test4</span>
<span class="box-header red">test5</span>
<span class="box-header red">test6</span>
<span class="box-header checked">test7</span>
</div>
Solution 1:[1]
I hope this code will fulfill your problem
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script>
$('.cover-header').scroll(function(){
$('.cover-header>span').each(function(){
var x = $(this).position();
if(x.top < 10){
console.log(x.top);
$('.box-header').removeClass('red').removeClass('checked');
$(this).addClass('red').next().addClass('checked');
}
});
});
</script>
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Aman Kumar Sharma |
