How to toggle class after 100vh scroll

Kevin Brandao da Graca picture Kevin Brandao da Graca · Nov 4, 2014 · Viewed 16.7k times · Source

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");
        }
    });
});

Answer

Roko C. Buljan picture Roko C. Buljan · Nov 4, 2014

100vh in jQuery is simple as $(window).height() while in pure JavaScript is window.innerHeight or a bit more longer.

jsFiddle demo

jQuery(function($) {

    var $nav = $('#verschwinden');
    var $win = $(window);
    var winH = $win.height();   // Get the window height.

    $win.on("scroll", function () {
        if ($(this).scrollTop() > winH ) {
            $nav.addClass("doch");
        } else {
            $nav.removeClass("doch");
        }
    }).on("resize", function(){ // If the user resizes the window
       winH = $(this).height(); // you'll need the new height value
    });

});

you can also make the if part a bit shorter by simply using:

$nav.toggleClass("doch", $(this).scrollTop() > winH );

demo