views:

637

answers:

2

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.

A: 

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

Anatoliy
A: 

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:

karim79
Thanks for your reply! I got that operational, but being completely new to the world of jquery and javascripting, I'm unsure where to go from here. The box does fade or scroll, but it seems to stay faded regardless if I scroll to the top again. And how can I control how far one has to scroll before it fades? Thanks again!!
Unfortunately, short of providing you with a complete solution, there's not much more help that can be given. If you're really interested in getting this working you'll probably have to dig in and learn some JavaScript.
Peter Wagenet