Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fading Element on Scroll

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.

like image 354
marck Avatar asked Sep 27 '09 20:09

marck


2 Answers

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:

  • jQuery
  • Selectors
  • CSS
  • Events/Scroll
  • CSS/ScrollTop
  • CSS/ScrollLeft
like image 93
karim79 Avatar answered Sep 22 '22 17:09

karim79


I thought I would give it a go using the actual value of scrollTop to dictate the opacity level, thus getting a smooth fade. I also added the hover state for the second part. Thanks to David for refining the maths for me.

//reduce the opacity of the banner if the page is scrolled.
$(window).scroll(function () {
  var height = $("body").height();
  var scrollTop = $("body").scrollTop();
  var opacity = 1;

  if(scrollTop < 41)
    {opacity = 1-Math.floor(scrollTop)/100;}
    else
    {opacity = 0.6;}

  $("#header").css("opacity", opacity);
  $("#header").hover(function(){
    $(this).css("opacity", 1);
    },function(){
    $(this).css("opacity", 0.6);
    });
});
like image 20
Daniel Avatar answered Sep 22 '22 17:09

Daniel