Search code examples
jquerycssscrollfade

Jquery fade in div as I scroll down


I found this on another post and it works great except I need to reverse it so that when I scroll "down" it fades in the div.

var target = $('#bluOverlay');
var targetHeight = target.outerHeight();

$(document).scroll(function(e){
    var scrollPercent = (targetHeight - window.scrollY) / targetHeight;
    if(scrollPercent >= 0){
        target.css('opacity', scrollPercent);
    }
});

Here is the working fiddle from the other post http://jsfiddle.net/meEf4/


Solution

  • You can set the opacity of the div to zero initially and then when scrolled down increment the opacity gradually.

    Demo

    var target = $('div'),
      targetHeight = target.outerHeight();
    
    $(document).scroll(function(e) {
      var scrollPercent = (targetHeight - window.scrollY) / targetHeight;
    
      if (scrollPercent >= 0) {
        target.css('opacity', 1 - scrollPercent);
      }
    });
    body {
      height: 3000px
    }
    div {
      height: 1000px;
      background: red;
      opacity: 0;
    }
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.0/jquery.min.js"></script>
    <div></div>