Keep the footer at the bottom with Javascript

Keaire picture Keaire · May 16, 2015 · Viewed 13.3k times · Source

At the moment I'm trying to keep the footer at the bottom with Javascript. This is the result:

document.getElementsByTagName('body').onload = function() {KeepFoot()};
var element = document.getElementById('container');
var height = element.offsetHeight;

function KeepFoot() {
    if (height < screen.height) {
        document.getElementById("footer").style.position = "fixed";
        document.getElementById("footer").style.bottom = "0";
        document.getElementById("footer").style.left = "0";
        document.getElementById("footer").style.right = "0";
    }
}

My idea was to take the height of the div container and compare it with the height of the resolution of the pc. If the height of the div container is smaller than the height of the resolution of the PC, set to the div footer position: fixed;

But there is a problem in the script because it doesn't work.

Another question, the script that I created would be fine for keep the footer at the bottom?

HTML:

<html>
    <head>
        ...
    </head>
    <body>
        <div id="container">
            <div id="header"></div>
            <div id="content"></div>
            <div id="footer"></div>
        </div>
    </body>
</html>

Answer

Ganesh Uppinivalasa picture Ganesh Uppinivalasa · May 16, 2015

The function is not being called on load. You can attach the function KeepFoot directly to the body tag like this Instead of calling like this:

 document.getElementsByTagName('body').onload = function() {KeepFoot()};

or use my code from below:

 (function() {
    var offsetHeight = document.getElementById('container').offsetHeight;   
    var screenHeight = screen.height;

if(offsetHeight < screenHeight){
    document.getElementById("footer").style.position = "fixed";
    document.getElementById("footer").style.bottom = "0";
    document.getElementById("footer").style.left = "0";
}
})();