Home > database >  How to transfer the existing class to the next order div and add a new class?
How to transfer the existing class to the next order div and add a new class?

Time:03-14

I have a question. I created a page with the following structure.

<div >
  <span >test1</span>
  <span >test2</span>
  <span >test3</span>
  <span >test4</span>
  <span >test5</span>
  <span >test6</span>
  <span >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 >
  <span >test1</span>
  <span >test2</span>
  <span >test3</span>
  <span >test4</span>
  <span >test5</span>
  <span >test6</span>
  <span >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 >
  <span >test1</span>
  <span >test2</span>
  <span >test3</span>
  <span >test4</span>
  <span >test5</span>
  <span >test6</span>
  <span >test7</span>
</div>

CodePudding user response:

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>
  • Related