marck
marck

Reputation: 143

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.

Upvotes: 6

Views: 11368

Answers (3)

Daniel
Daniel

Reputation: 792

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);
    });
});

Upvotes: 2

karim79
karim79

Reputation: 342635

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:

Upvotes: 8

Anatoliy
Anatoliy

Reputation: 30073

Use scroll event, and analyse value of document.documentElement.scrollTop to set appropriated opacity. http://www.quirksmode.org/dom/events/scroll.html

Upvotes: 0

Related Questions