Fading scroll element

I am curious how I can create a DIV (or something really) that I can fade out (or change the opacity) when the user scrolls down the page. This DIV will sit at the top of the page, but will only be clearly visible when it is at the very top of the page.

In addition, it would be ideal if I could return this element to onmouseover, regardless of the current scroll position on the page.

+6
javascript visibility html scroll fade
source share
3 answers

jQuery will allow you to use a compressed solution, hiding most browser inconsistencies. Here is a quick layout 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:

+8
source share

I thought that I would let him go using the actual scrollTop value to dictate the level of opacity, thereby getting a smooth fading. I also added a hang state for the second part. Thanks to David for improving math 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); }); }); 
+2
source share

Use the scroll event and analyze the value of document.documentElement.scrollTop to set the corresponding opacity. http://www.quirksmode.org/dom/events/scroll.html

0
source share

All Articles