Tobias Glaus
Tobias Glaus

Reputation: 3628

Fade out section on page top, fade in on bottom

I got this codepen: https://codepen.io/tobiasglaus/pen/NpVXRR
When I scroll the first section fades out and the second one fades in from the bottom with this code:

$(window).scroll(function(){
    $(".top").css("opacity", 1 - $(window).scrollTop() / 400);
  });
$(window).scroll(function(){
    $(".bottom").css("opacity", 0 + $(window).scrollTop() / 400);
  });

But that's just a scroll event and only working with 2 sections. Is there a way that I can add more sections and they just fade out, when they reach the top and fade in from the bottom?

Upvotes: 0

Views: 1851

Answers (1)

King King
King King

Reputation: 63327

As I understand you want something like this: when an element comes into the viewport area, it's faded in and when it comes out of the viewport area, it should be faded out.

So all the thing should be done in the onscroll event of the window. To know if the element is in and out of the viewport area we need to know about its top and bottom (which can be calculated from its top and its height), we also need to know about the viewport's height. That's all we need to find out if an element is in or out the viewport area. The following is the detailed code. NOTE: I don't include the complexity of getting the viewport's height here for simplicity (I just use document.documentElement.clientHeight - which should work in the latest versions of all modern browsers today).

HTML:

<div class="fading"></div>
<div class="fading"></div>
<div class="fading"></div>
<div class="fading"></div>

CSS:

.fading {
  border:1px solid red;
  margin-bottom:10px;
  height:500px;
  background:green;
}

JS:

var fadings = $(".fading");
$(window).scroll(function(){
  //the viewport's height
  var vpheight = document.documentElement.clientHeight;
  //loop through all interested elements
  fadings.each(function(){
    //get the rect of the current element
    var r = this.getBoundingClientRect();
    //the current element's height  
    var thisHeight = $(this).height();
    //check if the element is completely out of the viewport area
    //to just ignore it (save some computation)
    if(thisHeight + r.top < 0 || r.top > vpheight) return true;
    //calculate the opacity for partially visible/hidden element
    var opacity = Math.max(0, Math.min(1, 
                  (r.top >= 0 ? vpheight - r.top : thisHeight - Math.abs(r.top)) / vpheight));
    //set the opacity
    $(this).css("opacity", opacity);
  });           
});

Demo

Upvotes: 3

Related Questions