Michael Peters
Michael Peters

Reputation: 39

Nav Bar Scroll Function NOT Working

What I need to do to change the colour of my nav bar when I scroll down by a certain amount and reset when I scroll back up. I have tried many different techniques. AKA youtube videos on the subject. But cannot seem to get it to work! I have a 'scrolled' class in my CSS stylesheet with a background color set. But it won't even take my function.

$(function(){
    $(window).scroll(function() {
        if($(window).scrollTop() >= 100) {
            $('.nav').addClass('scrolled');
        }else {
            $('.nav').removeClass('scrolled');
        }
    });
});

Google Chrome Dev-Files

Upvotes: 0

Views: 307

Answers (3)

hemantjadon
hemantjadon

Reputation: 1

This describes how to implement this in Vanilla JS, also taking care of performance using passive event listeners.

Codepen Links

let navRef = document.querySelector('nav');

document.addEventListener('scroll', () => {
  if (window.scrollY > 500) {
    navRef.classList.add('scrolled');
  } else {
    navRef.classList.remove('scrolled');
  }
}, { passive: true })
body {
  margin: 0;  
}

div.container {
  background: aliceblue;
  height: 10000px;
}

nav {
  height: 50px;
  background: pink;
  position: fixed;
  width: 100vw;
  transition: background 0.3s ease-in-out;
}

nav.scrolled {
  background: #80deea;
}
<div class="container">
  <nav></nav> 
</div>

Upvotes: 0

Eric
Eric

Reputation: 2705

Not sure what the outermost $(function() {... does, but I think that was the reason the snippet inside did not run.

//$(function(){
    $(window).scroll(function() {
        if($(window).scrollTop() >= 100) {
            $('.nav').addClass('scrolled');
        }else {
            $('.nav').removeClass('scrolled');
        }
    });
//});
.nav {
  max-width: 500px;
  height: 1000px;
}

.nav.scrolled {
  background-color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="nav">
</div>

If you intended to use IIFE, immediately invoked function expression, you can do

(function(){
    $(window).scroll(function() {
        if($(window).scrollTop() >= 100) {
            $('.nav').addClass('scrolled');
        }else {
            $('.nav').removeClass('scrolled');
        }
    });
}());

which also works.

Upvotes: 0

Michael Peters
Michael Peters

Reputation: 39

//$(function(){
    $(window).scroll(function() {
        if($(window).scrollTop() >= 100) {
            $('.nav').addClass('scrolled');
        }else {
            $('.nav').removeClass('scrolled');
        }
    });
//});
.nav {
  max-width: 500px;
  height: 1000px;
}

.nav.scrolled {
  background-color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="nav">
</div>
THANKS SO MUCH!

Upvotes: 1

Related Questions