Search code examples
javascriptscrollfade

How to make section fade on scroll?


I am trying to make a section of my website fade out on scroll. I tried looking at other questions, but none helped. Here is the link to my code : http://bit.ly/1BmYnvo

Any help would be appreciated. If you could tell me why your code works, that would be great too!

Thanks


Solution

  • In your js, you're trying to select element(s) with .social class. The class is not set anywhere, therefore jQuery won't select any element, thus not changing opacity value on scroll.

    Fix: add class="social" to your div.

    // As @Bojangles recommended, search for element only once to improve performace.
    var $socialDiv = $('.social');
     
    $(window).scroll(function() {
      //Get scroll position of window 
      var windowScroll = $(this).scrollTop();
    
      //Slow scroll of social div and fade it out 
      $socialDiv.css({
        'margin-top': -(windowScroll / 3) + "px",
        'opacity': 1 - (windowScroll / 550)
      });
    });
    div {
      position: absolute;
      left: 0;
      top: 0;
      width: 100%;
      height: 500%;
      background: red;
    }
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <div class="social">
      Hi!
    </div>