I have a div covered by another div, and I'm trying to get the cover to fade away (revealing the div beneath) once the bottom of the window is greater than halfway down the div. I was able to get it to work for fading once the top hit the top of the window, but i've edited it since then and it doesn't work anymore.
Here is a JSfiddle example: http://jsfiddle.net/DnJ2z/676/
and here is my JavaScript code:
$(document).ready(function() {
var scrollBottom = $(window).scrollTop() + $(window).height();
var middleofDiv = $("#redCover").offset().top + (document.getElementById('redCover').clientHeight/2);
$(window).scroll(function() {
if(scrollBottom > middleofDiv) { //scrolled past the other div?
$("#redCover").fadeOut(2000); //reached the desired point -- show div
}
});
});
For this example, I want it so that when the bottom of the window is more than halfway down the green div, the fade is triggered.
As a side note, I have three of these Div+coveredDiv on the page, all of class "background" and "cover". If I can get this Javascript to work, is there a way to make it work for all of the class instead of individual elements?
Thanks for any help you can give!
Your problem is that scrollTop()
is different depending on where you scroll to. You're running it onload
, so it's always the same. It need to run in your scroll
Event. Try this:
$(function(){
var rC = $('#redCover'), middleofDiv = rC.offset().top + (rC.height()/2);
$(window).scroll(function(){
if($(window).scrollTop() + $(window).height() > middleofDiv){
//scrolled past the other div?
rC.fadeOut(2000); //reached the desired point -- show div
}
});
});
As promised:
$(window).scroll(function(){
var sT = $(window).scrollTop(), wH = $(window).height();
$('.color').each(function(){
var ths = $(this);
if(sT + wH > ths.offset().top + (ths.height()/2)){
ths.fadeOut(2000);
};
});
});
Note, that you do have #greenDiv
around #redCover
.