Difference between window height and document height04:33

  • 0
Published on October 19, 2017

Link for all dot net and sql server video tutorial playlists

Link for slides, code samples and text version of the video

In this video we will discuss
1. Difference between window height and document height
2. How to detect if the user has scrolled to the bottom of the page

$(window).height() – Returns height of the browser window i.e browser viewport
$(document).height() – Returns height of HTML document
$(window).scrollTop() – Returns the current vertical position of the scroll bar

What is the difference between window height and document height
The window height is what you see (i.e browser viewport), but the document height includes everything below or above the visible area.

How to detect if the user has scrolled to the bottom of the page
Here is the formula to detect if the user has scrolled to the bottom of the page

if (verticalScrollBarPosition == $(document).height() – $(window).height()) {
floatingDiv.html(‘Reached the bottom of the page’);
}

Why window height and document height are the same in Google chrome
Without DOCTYPE tag Chrome reports the same value for both window height and document height. Include the following DOCTYPE declaration
<!DOCTYPE html>

Example used in the demo

<!DOCTYPE html>
<html>
<head>
<script src=”jquery-1.11.2.js”></script>
<script type=”text/javascript”>
$(document).ready(function () {
var floatingDiv = $(“#divfloating”);
var floatingDivPosition = floatingDiv.position();
$(window).scroll(function () {
var scrollPosition = $(window).scrollTop();
if (scrollPosition >= floatingDivPosition.top) {
floatingDiv.css({
‘position’: ‘fixed’,
‘top’: 3
});
} else {
floatingDiv.css({
‘position’: ‘relative’,
‘top’: 0
});
}

floatingDiv.html(‘Window Height = ‘ + $(window).height() + ‘<br/>’ +
‘Document Height = ‘ + $(document).height() + ‘<br/>’ +
‘Vertical Scrollbar Position = ‘ + scrollPosition
);

if (scrollPosition == $(document).height() – $(window).height()) {
floatingDiv.html(‘Reached the bottom of the page’);
}
});
});
</script>
</head>
<body style=”font-family:Arial;”>
<table align=”center” border=”1″ style=”border-collapse:collapse”>
<tr>
<td style=”width:500px”>
<div>
Main Page Content
</div>
</td>
<td style=”width:150px; vertical-align:top”>
Side panel content
<br /><br />
<div id=”divfloating” style=”background-color:silver; width:150px; height:150px”>
Floating Div – Keeps floating as you scroll down the page
</div>
</td>
</tr>
</table>
</body>
</html>

In our next video we will discuss how to load data like facebook as you scroll down the page.

Enjoyed this video?
"No Thanks. Please Close This Box!"