Skip to content Skip to sidebar Skip to footer

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

Solution 1:

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>

Solution 2:

Use a percentage of the window height to compare

$(window).scroll(function() {    
    var height = $(window).height(),
        scroll = $(window).scrollTop()
        limit = 0.6; //implies 60 vh or 60% of viewport height

    if (scroll >= height*limit) {
        $(".clearHeader").addClass("darkHeader");
    } else {
        $(".clearHeader").removeClass("darkHeader");
    }
});

and even better would be to update some variable only when the window is resized to avoid computations all the time

var limit = 0.6, //implies 60 vh or 60% of viewport height
    scrollLimit = 0;

$(window).resize(function(){
          scrollLimit = $(window).height() * limit;
       }).scroll(function() {    
          var scroll = $(window).scrollTop(); 

          if (scroll >= scrollLimit ) {
              $(".clearHeader").addClass("darkHeader");
              } else {
              $(".clearHeader").removeClass("darkHeader");
          }
       }).trigger('resize').trigger('scroll'); // trigger both events on start to force initial setup

Solution 3:

Try something like this

$(window).scroll(function() {    
    var scroll = $(window).scrollTop();

    if (scroll >= 500) {
        $(".clearHeader").addClass("darkHeader");
    } else {
        $(".clearHeader").removeClass("darkHeader");
    }
});

Solution 4:

For retrieveing the viewport Height, you could use $(window).innerHeight():

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

Hope this helps.

Leo.


Post a Comment for "Jquery Add CSS Class After 'X' Amount Of Viewport Height Scrolled"