Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to dynamically select previous sibling element

I have a problem with the implementation of 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 have selected (active) link. I need add same (active) class to previus link when user scroll at top of document. This example have active #page-link-7. Previus is 6. So when user scroll at top, class "active" will be added for #page-link-6. But if current active page-link is 9, how can i go to 8 dynamically? I hope someone can help me here. Thanks.

like image 409
Arriba Avatar asked Aug 31 '26 13:08

Arriba


1 Answers

Find the element that is currently active, then use jQuerys .prev() method to find the "previous" link. Something along the likes of

$('.active').prev().addClass("active" );
like image 179
Craicerjack Avatar answered Sep 03 '26 05:09

Craicerjack



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!