Skip to content

Instantly share code, notes, and snippets.

@sAVItar02
Created July 14, 2021 21:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sAVItar02/548ca605038a898034183e7676d3faac to your computer and use it in GitHub Desktop.
Save sAVItar02/548ca605038a898034183e7676d3faac to your computer and use it in GitHub Desktop.
Change background color of the navbar on scroll
// JQuery
$(function (){
$(document).scroll(function(){
var $nav = $(".nav");
$nav.toggleClass("scrolled", $(this).scrollTop() > $nav.height()); // in the class "scrolled" set a different background color
});
});
// Vanilla
window.onscroll = function() {
let top = window.scrollY;
let navHeight = 100 //set nav height or the number of pixels to scroll before color change
const nav = document.querySelector("nav");
if(top >= navHeight) {
nav.classList.add("active"); // in the active class set a different color for the navbar
} else {
nav.classList.remove("active");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment