How to dynamically select the previous sibling element

I have a problem implementing non-standard solutions. So my HTML:

<a href="#6" id="page-link-6">6</a>
<a href="#7" id="page-link-7" class="active">7</a>
<a href="#8" id="page-link-8">8</a>

      

And my poor, incompetent js:

$(window).scroll(function() {   
   if($(window).scrollTop() + $(window).height() > $(document).height() - 0) {
        $("#page-link-6").addClass("active" );
   }
});

      

I selected the (active) link. I need to add the same (active) class to the previus link when the user scrolls to the top of the document. This example has active # page-link-7. Previus is 6. So when the user scrolls up, the "active" class will be added for # page-link-6. But if the currently active link page is 9, how can I jump to 8 dynamically? Hope someone can help me. Thank.

+3


source to share


3 answers


What you can do is just find the link next

and previous sibling

of active

and add a class to it like below:

Wrap it all up <a>

in separateclass

<div class="Links">
   <a href="#6" id="page-link-6">6</a>
   <a href="#7" id="page-link-7" class="active">7</a>
   <a href="#8" id="page-link-8">8</a>
</div>

      

Js



var activeLink=$('.Links').children().find('.active').removeClass('active');
if($(window).scrollTop() + $(window).height() > $(document).height() - 0) 
{
      $(activeLink).prev().addClass('active');
}
else
{
     $(activeLink).next().addClass('active');
}

      

UPDATE

DEMO

$(window).on('scroll',function(){
    var activeLink=$('.Links').find('.active');
    if($(window).scrollTop() + $(window).height() > $(document).height() - 0) 
    {

          if($(activeLink).prev().length>0)
          {
             $(activeLink).removeClass('active');
             $(activeLink).prev().addClass('active');
          }
    }
    else
    {
        if($(activeLink).next().length>0)
        {
            $(activeLink).removeClass('active');
            $(activeLink).next().addClass('active');
        }
    }
});

      

0


source


Find the active item, then use the jQuerys method .prev()

to find the "previous" link. Something like



$('.active').prev().addClass("active" );

      

+1


source


I don't really understand your question, but it sounds like . toggleClass () might be better for you.

$('a').on('click', function (e) {
    $('a').toggleClass("active");
});

      

Simple demo script .

0


source







All Articles