Sticky nav bar when it reaches the top on scroll down

Just make a simple POC for my General Assembly FEWD student.
sticky-nav-bar-on-scrolldown
 

Create the following files within the same folder

index.html

<!DOCTYPE html>
<html>
<head>
  <title></title>
  <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
  <link rel="stylesheet" type="text/css" href="styles.css">
</head>
<body>
  <header></header>
  <nav>123</nav>
  <div id="container">
    <div>Scroll down!</div>
    <h1>H</h1><h1>E</h1><h1>L</h1><h1>L</h1><h1>O</h1> <h1>W</h1><h1>O</h1><h1>R</h1><h1>L</h1><h1>D</h1><h1>!</h1>
  </div>
  <script type="text/javascript" src="script.js"></script>
</body>
</html>

 

styles.css

body {
  margin: 0;
  padding: 0;
}

header {
  margin: 0;
  padding: 0;
  background-color: red;
  height: 100px;
}

nav {
  background-color: black;
  height: 40px;
  width: 100%;
}

#container {
  background-color: green;
  height: 2000px;
}

/* Sticky scrollbar on scroll down */
nav.sticky {
  position: fixed;
  top: 0;
}

#container.offset {
  padding-top: 40px;
}

 

script.js

$(window).scroll(function() {
  // get the scroll position
  var height = $(window).scrollTop();
  
  // Output the height for debug
  console.log(height);

  if (height > 100) {
    // make the nav bar stick at the top
    $("nav").addClass("sticky");
    $("#container").addClass("offset");
  } else {
    // reset the nav bar
    $("nav").removeClass("sticky");
    $("#container").removeClass("offset");
  }
});

 

Done =)

Advertisement

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.