I am trying to calculate the percentage number (0.0 - 2.0 / 0% - 200%) so that I can change the opacity of the div when it comes in and out of view.
- When the window is above the scope, the percentage is equal to or less than 0
- When the window is in the exact center of the visible area, the percentage is 1.0
- And when the window is below visibility, the percentage is 2.0 and up
And when scrolling and exiting the view, this will be part of it.
Somehow I need to compare the vertical center of the window with the vertical center of the area, but it's hard for me to get the correct calculations.
I still have
var p = { scrollTop: $(window).scrollTop(), documentHeight: $(document).height(), windowHeight: $(window).height(), contentTop: $('.content').position().top, contentHeight: $('.content').height() }; if (p.windowHeight / 2 + p.scrollTop < p.contentHeight / 2 + p.contentTop) { p.percent = (p.windowHeight / 2 + p.scrollTop) / (p.contentHeight / 2 + p.contentTop); } else if (p.windowHeight / 2 + p.scrollTop > p.contentHeight / 2 + p.contentTop) { p.percent = (p.windowHeight / 2 + p.scrollTop) / (p.contentHeight / 2 + p.documentHeight - p.contentHeight - p.contentTop); } else p.percent = 1; $('.content').animate({ opacity: 1 - Math.abs(p.percent - 1) }, 1);
But I do not factorize the height of the document, so I know that something is missing. I also feel that this can be done in one equation without if / else
Here's a non-functioning fiddle I'm working on: http://jsfiddle.net/nxdTn/
To better demonstrate, see the examples below.
Yellow is the document, transparent gray is the window, and blue is the visible area.
Blue will be 0 opacity: 
At 100% Opacity: 
And back to 0: 
source share