Sam Assoum Sam Assoum - 1 month ago 5
Javascript Question

Jquery add CSS class after 'X' amount of viewport height scrolled

So I have this jQuery function that adds / removes a CSS class to an element after 600px of the viewport height has been scrolled.

$(window).scroll(function() {
var scroll = $(window).scrollTop();
if (scroll >= 600) {
$(".cta_box").addClass('fadeout');
} else {
$(".cta_box").removeClass('fadeout');
}
});


I'd like to tweak it so instead of working based off a pixel value, it works off of the view height css measurement "VH", but the equivalent results are what matter in this case.

Answer

It can be done by getting the window height using $(window).height().

For instance suppose you have to scroll half the screen more (height is 150vh) and you have to detect when 40% has been scrolled:

$(window).scroll(function() {    
    var scroll = $(window).scrollTop();    
    if (scroll >= 0.4 * $(window).height()) {
        $(".cta_box").addClass('fadeout');
    } else {
        $(".cta_box").removeClass('fadeout');
    }
});
body{
  margin: 0;
  height: 150vh;
}
.cta_box {
  height: 100%;
  background: green;
}
.cta_box.fadeout {
  background: grey;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div class="cta_box"></div>

Comments