Increase the transparency of the div when scrolling down

I have researched the lost sources but there is no solution for my problem. I created a div and its visibility is hidden in CSS sources. I want to start it at 0.1 opacity when scrolling through 200, and when the scroll positioned at 300 opacity becomes 1.

$(document).ready(function(){                    
    $(window).scroll(function(){
        if ($(this).scrollTop() > 150) {
            $('.fscrollonh').css({"opacity": "0.1",  "visibility": "visible"});
            $('.fscrollonh').show(500);
        } else {
            $('.fscrollonh').hide(500);
        }
    });
});

      

+3


source to share


2 answers


I'm guessing you are looking for something like this?



$(document).ready(function(){                    
    $(window).scroll(function(){
      let sT =  $(window).scrollTop();
      $('.scrollonh').css({
        opacity: (sT < 201 ? 0 : (sT > 300 ? 1 : (sT - 200)/100))
      })
    });
});
      

body {
  min-height: 200vh;
}
.scrollonh {
  position: fixed;
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
  opacity: 0;
  display: flex;
  justify-content: center;
  align-items: center;
}
.\32 00pxmark, 
.\33 00pxmark {
  margin-top: 200px;
  height: 0;
  overflow: visible;
  border-top: 1px solid red;
}
.\33 00pxmark {
  margin-top: 100px;
}
      

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="scrollonh">I fade on scroll</div>
<div class="200pxmark">200px mark</div>
<div class="300pxmark">300px mark</div>
      

Run codeHide result


+3


source


Try it. It calculates the opacity based on the function and scrolling calculation

$(document).ready(function(){                    
    $(window).scroll(function(){
      var scrollval =   $(this).scrollTop();
      if ( scrollval > 150) {
            $('.fscrollonh').css({"visibility": "visible"});
            $('.fscrollonh').show(500);
            $('.fscrollonh').css({
                opacity: function() {
                 var opacity = (150 * .006) + 0.1;
                 return opacity;
                 }
              });
        }
    else {
            $('.fscrollonh').hide(500);
        }
    });
});

      



Although I haven't tried it yet.

Hopt helps.

0


source







All Articles