Reputation: 2983
While trying to solve this issue, I was only running into jQuery plugins. But due to my site being tiny, I only use the jQuery alternative cash.
I would like to achieve the following behavior:
From what I read from the jQuery plugins, I'd need to calculate the height of my content, subtract that from the current viewport and see if the result is negative or not.
But since I don't use jQuery, how'd I do that?
My HTML's structure is (similar to) this:
<!DOCTYPE html>
<html>
<head>
<title>...</title>
</head>
<body>
<div id="MainPage">
<div class="menu"></div>
<div class="content"></div>
</div>
<footer></footer>
</body>
</html>
Everything except the footer is in a wrapping div
.
Upvotes: 1
Views: 797
Reputation: 15070
A good example (when knowing the height of your footer) is the Ryan Fait's HTML5 Sticky Footer.
http://ryanfait.com/html5-sticky-footer/
<body>
<div class="wrapper">
<div class="push"></div>
</div>
<footer></footer>
</body>
* {
margin: 0;
}
html, body {
height: 100%;
}
.wrapper {
min-height: 100%;
margin: 0 auto -155px; /* the bottom margin is the negative value of the footer's height */
}
footer, .push {
height: 155px; /* '.push' must be the same height as 'footer' */
}
<body>
<footer></footer>
</body>
html {
position: relative;
min-height: 100%;
}
footer {
position: absolute;
bottom: 0;
width: 100%;
}
$( 'body' ).css( 'margin-bottom', $( 'footer' ).height() );
document.getElementsByTagName('body')[0].style.marginBottom = document.getElementsByTagName('footer')[0].offsetHeight + 'px';
Upvotes: 2
Reputation: 1643
window.innerHeight
gives you the height of the screen, getElementById().height
gives you the height of an element.
So in your case you'd have in plain JS:
if (document.getElementById('MainPage').offsetHeight < window.innerHeight) {
document.getElementsByTagName('footer')[0].style.position='fixed';
}
Or you can add a class 'fixedFooter' instead of setting a CSS-property with document.getElementsByTagName('footer')[0].classname += ' fixedFooter';
and style this class via CSS. That will give you more controll. E.g.:
.fixedFooter {
bottom: 0;
position: fixed;
}
Upvotes: 1
Reputation: 798
You can get the height of the browser window (without scrollbars/toolbars) using:
window.innerHeight
Then you can get the height of the MainPage div using:
document.getElementById("MainPage").offsetHeight
Note that window.innerHeight will include the height of the horizontal scrollbar if one is present on the page, so account for it if you need to.
Once you have those two properties, you can calculate the sizes you need.
If all you want to do is stick the footer to the bottom of the page, you can also use CSS, e.g.
footer{
position: fixed;
bottom: 0px;
}
Upvotes: 2