Fading Element on Scroll

marck picture marck · Sep 27, 2009 · Viewed 11.1k times · Source

I'm curious how I can create a DIV (or anything really) that I can fade (or change opacity of) when a user scrolls down the page. This DIV would sit at the top of the page, but only be clearly visible when at the very top of the page.

Additionally, it would be ideal if I I could have this element fade back in onmouseover, regardless of the current scrolled position on the page.

Answer

karim79 picture karim79 · Sep 28, 2009

jQuery would allow for a succinct solution, whilst hiding most browser discrepancies. Here's a quick mock-up to get you started:

<script type="text/javascript">

    //when the DOM has loaded
    $(document).ready(function() {

        //attach some code to the scroll event of the window object
        //or whatever element(s) see http://docs.jquery.com/Selectors
        $(window).scroll(function () {
              var height = $('body').height();
              var scrollTop = $('body').scrollTop();
              var opacity = 1;

              // do some math here, by placing some condition or formula
              if(scrollTop > 400) {
                  opacity = 0.5;
              }

              //set the opacity of div id="someDivId"
              $('#someDivId').css('opacity', opacity);
        });
    });
</script>

See also: