Pho Ga
Pho Ga

Reputation: 29

Making div fade in and out when scrolling

I have a div that is set to:

{
  height: 100vh;
  width: 100%;
  background-color: black;
  opacity: 0;
  position: absolute;
  z-index: 2;
}

This div is also at the top of the page. I want to make it so that as I scroll down (and away from the div), it slowly fades in, and when I scroll back up it fades out.

How would I do this?

Upvotes: 1

Views: 684

Answers (2)

Simon Pasku
Simon Pasku

Reputation: 649

 document.body.addEventListener('wheel', (e) => {
                                    let faceLayer = document.getElementById('your_id');
                                    faceLayer.style.opacity = Math.abs(Math.max(faceLayer.getBoundingClientRect().top, 0) / faceLayer.clientHeight).
                                })

Upvotes: 1

Mayur Patil
Mayur Patil

Reputation: 11

You may refer following code snippet. The point I am trying to make is in the script tag at the bottom just added the window scroll function which sets the opacity to your entire window of desired height in your css class ".top". So when you try to scroll in and out it will dynamically add an animation effect to your window.

<html>

<head>
  <script src="https://code.jquery.com/jquery-3.3.1.min.js" integrity="sha256FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8=" crossorigin="anonymous"></script>
  <style>
    body {
      margin: 0;
      height: 1000px;
    }
    
    .top {
      margin: 0;
      position: relative;
      width: 100%;
      background-color: #aaa;
      height: 300px;
      opacity: 1;
      text-align: center;
      font-family: 'helvetica';
      font-size: 80px;
      font-weight: 100;
      color: #fff;
    }
    
    .title {
      position: absolute;
      top: 60%;
      left: 100px;
    }
  </style>
</head>

<body>
  <div class="top">
    <div class="title">Fade Away</div>
  </div>
</body>

</html>

<script>
  $(window).scroll(function() {
    $(".top").css("opacity", 1 - $(window).scrollTop() / 250);
  });
</script>

Upvotes: 1

Related Questions