Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

add or remove class to div when scrolling page between anchors

I am developping a condition for my site, so that when i scroll my page to an anchor, the menu item corresponding to that anchor adds or removes a certain class.

My problem is that i can't make the first item menu remove class, when scrolling to the second anchor, i think the problem may be in the condition, it may not be working the way i think so i need your help

For this I am using jquery and here is what i've got so far:

jQuery(document).ready(function($) {

    var target1 = $("#thehotel").offset().top;
    var target2 = $("#thecity").offset().top;

    var interval = setInterval(function() {

         // i am not sure if this setInterval method is causing the problem, yet i didn't find any other solution

         if ($(window).scrollTop() >= target1 && $(window).scrollTop() < target2) {
              $("#menu .item-109 a").addClass("myClass");
              $("#menu .item-111 a").removeClass("myClass");

         }  
         else if ($(window).scrollTop() >= target2) {
             $("#menu.item-109 a").removeClass("myClass");
             $("#menu .item-111 a").addClass("myClass");
         }  



    }, 250);    
});

I apologize if you find my english bad, it's not my mother language. Thank you.

I found my error, it is a typo!

here:

           if ($(window).scrollTop() >= target1 && $(window).scrollTop() < target2) {
                  $("#menu .item-109 a").addClass("myClass");
                  $("#menu .item-111 a").removeClass("myClass");

             }  
             else if ($(window).scrollTop() >= target2) {

//change this        $("#menu.item-109 a").removeClass("myClass");

//to this            $("#menu .item-109 a").removeClass("myClass");

                 $("#menu .item-111 a").addClass("myClass");
             }  

The code is now working, sory for the trouble, Thank you all. Have a great day!

like image 220
BrunoMarques-BM Avatar asked Oct 21 '22 09:10

BrunoMarques-BM


1 Answers

Glad to see you figured it out. Instead of using setInterval() to run your code every 250ms you can attach an event handler to the window that will run your code every time you scroll allowing you to know exactly when you enter and leave the desired bounds.

$(window).on('scroll', function(){

    if ($(window).scrollTop() >= target1 && $(window).scrollTop() < target2) {

        $("#menu .item-109 a").addClass("myClass");
        $("#menu .item-111 a").removeClass("myClass");

    }else if ($(window).scrollTop() >= target2) {

        //change this        
        $("#menu.item-109 a").removeClass("myClass");

        //to this            
        $("#menu .item-109 a").removeClass("myClass");

        $("#menu .item-111 a").addClass("myClass");
    }
});
like image 180
Chris Traveis Avatar answered Oct 29 '22 18:10

Chris Traveis