imnewhere
imnewhere

Reputation: 53

Create a sliding navbar in jQuery

I'm trying to add CSS to my navbar so that when the user scrolls down the navbar background will slide from the top. Right now the background is just appearing with no transition. What am I missing?

Here's what I have written for jQuery:

$(function () {
    $(document).scroll(function () {
        const $nav = $(".navbar");
        $nav.toggleClass('scrolled', $(this).scrollTop() > $nav.height());
     });
});

SCSS:

.navbar { 
    position: fixed;
    z-index: 1;
    width: 100%;

    &.scrolled { 
        background-color: #FDFDFD;
        transition: background-color top 1s;
        padding-bottom: 24px;
        width: 100%;
    }
}

HTML:

<div class="navbar">
   <navbar class="grid-1">
      <img class="navbar-logo" src="#" alt="Website">
         <a class="navbar-links-li-1" href="#">Workshops</a> 
         <a class="navbar-links-li-2" href="#">Resources</a> 
         <a class="navbar-links-li-3" href="#">Donate</a> 
   </navbar>
</div>


<section class="main grid-1">
  <p>blah</p>
</section>

Upvotes: 2

Views: 148

Answers (1)

FluffyKitten
FluffyKitten

Reputation: 14312

You just need to add a transition rule to the navbar class, e.g. to set transitions on all properties for a duration of 0.5 seconds, use the following:

.navbar {
    transition: all 0.5s;
    // the rest of your CSS
}

Take a look at this CSS transitions page for more information.

Working example using the minimum of your code to illustrate the effect:

$(function () {
    $(document).scroll(function () {
        const $nav = $(".navbar");
        $nav.toggleClass('scrolled', $(this).scrollTop() > $nav.height());
     });
});
.navbar { 
    position: fixed;
    z-index: 1;
    width: 100%;
    transition: all 0.5s;
    background-color: #ccc;
 }
 .scrolled { 
    background-color: #FDFDFD;
    transition: background-color top 1s;
    padding-bottom: 24px;
    width: 100%;
}
.content {height:1000px; padding-top:50px;}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="navbar">NAV BAR </div>
<div class="content">
<p>Stuff here</p>
</div>

Upvotes: 1

Related Questions