javascriptjquerycssaddclass

addClass is not working


I'm making a nav bar so that when the user scrolls past a certain point, the style for the nav bar changes. To do this, I'm adding a class on the event that the user scrolls past "changePoint". For some reason the class added does not change the appearance (if it is even added). I know for a fact that the condition if (top > changePoint){ is running when it's meant to.

java script:

 $(window).on('scroll', function () {
    //top of the screen
    var top = Math.round($(window).scrollTop());

    //if past changePoint, change the style
    if (top > changePoint) {
        $(".navtop").addClass('changeStyle');
        //  window.alert('.navtop');
    } else {
        $('.navtop').removeClass('changeStyle');
    }
});

css:

.topnav {
font-family: 'Montserrat', sans-serif;
font-size: 16px;
margin: 20px;
background-color: transparent;
color: #fff;
transition: all 0.25s ease;
position: fixed;
top: 0;
width: 100%;
padding: 1em 0;
}

.topnav.changeStyle {
background-color: white;
color: #19CEC4;
}

html:

<!--navbar-->
<nav class="topnav">
    <img id=logo src="img/logo-big.svg" height="50px">
    <a href="#">Home</a>
    <a href="#">Events</a>
    <a href="#">About</a>
    <a href="#">Volunteer</a>
    <a href="#">Contact</a>
</nav>

<section id="home">
    <div class="jumbotron" id="jumbotronImg">
        <div class=container>
            <h1>Hi there!</h1>
            <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed consequat nibh ut fringilla imperdiet. Suspendisse potenti. Sed suscipit interdum ante eget ornare. Donec porttitor eros quam, eget fermentum neque sodales vel. Aenean fringilla id nisl nec finibus. Vivamus elementum lorem a mattis efficitur. </p>
        </div>
    </div>
</section>

Solution

  • In the jquery selector you've given as

    $(".navtop");
    

    But in the css you're using

    .topnav
    

    I'm not clear whether you mistyped here or else you're doing the same in your script cause i didn't get to see your html.

    Coming to your question, the css you've added will try to add this style to an element(child) having .changestyle class inside an element(parent) with .topnav class

    .topnav.changeStyle { background-color: white; color: #19CEC4; }

    Instead just add this

    .changeStyle { background-color: white; color: #19CEC4; }

    which will add this style to any element having this class