Reputation: 3428
Please consult this fiddle http://jsfiddle.net/abhicodes/LasxP/
Here I want to find out visible height of #content-wrapper
while each scroll.
#header
will always have same height and it will be fixed, but footer height is different in some of my pages, so I cannot take current footer height as a standard.
If I reach end of the page then most of the area is covered by footer, then also I want just the visible portion of #content-wrapper
and same to happen in rest of the scroll. For the rest of the page where footer is not visible I can subtract header height to get visible part.
Suppose if a we are at the bottom of the page and viewport height is 600px then I would like to find out how much area of #content-wrapper
is visible to a user. Because at that time footer is also there which accomodates 100px and header accomodates 80px, so total visible height of #content-wrapper
will be 600-180 = 420px and similarly if we are at top then footer is not there and just header is there, so visible area of #content-wrapper
will be 520px.
So, moral of the story is, I want to find out at any given instance during scroll how much height of #content-wrapper
is visible to a user if you take this fiddle in consideration
Upvotes: 0
Views: 7724
Reputation: 5841
The following will give you the visible height, and separates out the variables so the calculation makes sense:
$(document).on('scroll', function() {
//Container
var cont = $("#content-container");
//Scroll Position (varies with scroll)
var pageTop = $(document).scrollTop();
//Visible Page Size (fixed)
var pageSize = $(window).height();
//Header Height (fixed)
var headerHeight = $('#header').height();
//Content top (fixed)
var contTop = cont.offset().top;
//Content top position (varies with scroll)
var contTopPos = contTop - pageTop;
//Content bottom (fixed)
var contBottom = cont.height() + contTop;
//Content position in relation to screen top (varies with scroll)
var contBottomPos = contBottom - pageTop;
/*
VISIBLE AREA
Take the size of screen/page, unless the bottom of the content further up
and subtract from it
The header height, unless the top of the content is below the header
*/
var visibleArea = Math.min(pageSize, contBottomPos) - Math.max( headerHeight, contTopPos);
});
Example: http://jsfiddle.net/asifrc/LasxP/8/
Upvotes: 2
Reputation: 525
Try
var $win = $(window);
var $footer = $("#footer");
$(window).scroll(function(){
var windowHeight = $win.height();
var footerTop = $footer.offset().top - $win.scrollTop();
var visibleHeight = Math.min(windowHeight, footerTop) - 80;
console.log(windowHeight +", " + footerTop + ", " + visibleHeight);
});
The logic is simple.
[1]
or [2]
- header's height = your answer. Upvotes: 4