graememscott / company-site

0 stars 0 forks source link

Challenge #6: Changing Styles On Scroll #8

Open graememscott opened 5 years ago

graememscott commented 5 years ago

Changing Styles On Scroll with Vanilla Javascript

Step 1) Creating the markup

We are going to need a header element for our markup. We'll add a class and some text too for good measure:

<header class="header">
  Header
</header>

Step 2) Selecting our header element

We can use document.querySelector to get the element we created in the last step that has a class of "header". We'll put it inside a variable to make things easier for ourselves later on:

var header = document.querySelector(".header");

Step 3) Setting up an event listener for scrolling

To get the scroll event, we'll need to add an event listener to the window element that listens for the user to "scroll":

window.addEventListener("scroll", function() {
  // This will fire everytime we scroll!
});

Step 4) Getting the current scroll position

Since we know that there is only one window element, we don't need to bother with any "event" arguements, we can get the scroll position by getting the scrollY parameter from the window object:

var header = document.querySelector(".header");

window.addEventListener("scroll", function() {
  console.log(window.scrollY);
});

Step 5) Changing the Header on scroll

All we need now is to add a class to our header element once we have scrolled past the top of the page. scrollY starts at 0 so we can add a class if its more than 0, and remove it if it's less than or equal to 0:

var header = document.querySelector(".header");

window.addEventListener("scroll", function() {
  if (window.scrollY > 0) {
    header.classList.add('scrolled');
  } else {
    header.classList.remove('scrolled');
  }
});

Step 6) Have Fun!

Style the header! (Hint: Make it so the styles change depending on whether the ".scrolled" class is applied to the ".header" or not)

Get the code to add a class after you've scrolled over 100px! (Hint: we'll need to change our condition to check if scrollY is greater than 100)

Step 7) TLDR;

<header class="header">
  Header
</header>

<script>
  var header = document.querySelector(".header");

  window.addEventListener("scroll", function() {
    if (window.scrollY > 0) {
      header.classList.add('scrolled');
    } else {
      header.classList.remove('scrolled');
    }
  });
</script>