Search code examples
javascriptscrollheightviewport

How to toggle class after 100vh scroll


How to make this function add the class after scrolling 100vh?
Currently it adds the class after 850px.

$("document").ready(function($){
    var nav = $('#verschwinden');

    $(window).scroll(function () {
        if ($(this).scrollTop() > 850) {
            nav.addClass("doch");
        } else {
            nav.removeClass("doch");
        }
    });
});

Solution

  • In pure JavaScript use window.innerHeight to get the viewport height, and elScrollable.scrollTop to get the scrollTop of your element.
    Use classList.toggle("className", statement) to toggle a class:

    const elScrollable = document.querySelector("html")
    const elNav = document.querySelector("#nav");
    
    const handleNav = () => {
      const viewportHeight = window.innerHeight;
      const scrollTop = elScrollable.scrollTop;
      elNav.textContent = `Scrolled: ${scrollTop / viewportHeight}`
      elNav.classList.toggle("is-active", scrollTop >= viewportHeight);
    };
    
    addEventListener("scroll", handleNav)
    addEventListener("resize", handleNav)
    handleNav();
    * {
      box-sizing: border-box;
      margin: 0;
    }
    
    #nav {
      position: sticky;
      top: 0;
      background: silver;
    }
    
    #nav.is-active {
      background: gold;
    }
    <nav id="nav">NAV</nav>
    <p style="min-height: 300vh">
      scroll down until #nav becomes golden...
    </p>

    Using jQuery use $(window).height() to get the viewport height, and $scrollable.scrollTop() to get how much you scrolled the HTML (or any other) element.
    Use .toggleClass("className", statement) to toggle a class:

    const $window = $(window);
    const $scrollable = $("html");
    const $nav = $("#nav");
    
    const handleNav = () => {
      const viewportHeight = $window.height();
      const scrollTop = $scrollable.scrollTop();
      $nav
        .text(`Scrolled: ${scrollTop / viewportHeight}`)
        .toggleClass("is-active", scrollTop >= viewportHeight);
    };
    
    $window.on("scroll", handleNav)
    $window.on("resize", handleNav)
    handleNav();
    * {
      box-sizing: border-box;
      margin: 0;
    }
    
    #nav {
      position: sticky;
      top: 0;
      background: silver;
    }
    
    #nav.is-active {
      background: gold;
    }
    <nav id="nav">NAV</nav>
    <p style="min-height: 300vh">
      scroll down until #nav becomes golden...
    </p>
    
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script>