If li hasClass addClass to another div

10,571

Put your if condition inside the scrolling event handler, otherwise which will only executed once when the dom elements are loaded.

$(document).ready(function(jQuery) {
    var nav = $('.navigation-holder');
    $(window).scroll(function() {
        if ($(this).scrollTop() > 125) {
            nav.addClass("fix");
        } else {
            nav.removeClass("fix");
        }
        if ($(".menu-item-95").hasClass("act")) {
            $(".fix").addClass("darkmenu")
        }
    });
});

There is no need of "" for the document

Share:
10,571
Rob
Author by

Rob

Updated on June 04, 2022

Comments

  • Rob
    Rob almost 2 years

    My navigation get fixed by adding the class (.fix) when i scroll down. It has the following structure:

    <div class="navigation-holder fix">
        <div>
            <nav id="navigation">
                <ul id="main-nav">
                    <li class="menu-item-93" />
                    <li class="menu-item-95" />
                    <li class="menu-item-94" />
                    <li class="menu-item-96" />
                    <li class="menu-item-97" />
                    <li class="menu-item-98" />
                </ul>
            </nav>
        </div>
    </div>
    

    The li elements get automatically the class (.act) when they are active.

    This is the code for the fixed navigation.

    $("document").ready(function (jQuery) {
        var nav = $('.navigation-holder');
        $(window).scroll(function () {
            if ($(this).scrollTop() > 125) {
                nav.addClass("fix");
            } else {
                nav.removeClass("fix");
            }
        });
        if ($(".menu-item-95").hasClass("act")) {
            $(".fix").addClass("darkmenu")
        };
    });
    

    I'm trying to add another class (.darkmenu) to div (.fix) if li (95,96,98) has class (.act), but it doesn't work...

    • Mihir
      Mihir about 10 years
      Put your if condition inside the scroll function itself and verify whether it is working or not!
  • Rob
    Rob about 10 years
    Thank you, now it works perfectly. What do i need to add, if want to remove the class (.darkmenu) if one of the other li (93,94,97) is active?
  • Rob
    Rob about 10 years
    I'm using a onepage-template, so it must check every scroll step. Sorry i did not mentioned before.
  • dhana
    dhana about 10 years
    @PranavCBalan Excellent catch "" for the document