Keep footer below with javascript

I'm currently trying to save the footer below using 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 PC resolution height. If the height of the div container is less than the height of the PC resolution, set the footer position: fixed;

But the problem in the script arises because it does not work.

Another question the script I created would be good for the footer to be below?

HTML:

 <html> <head> ... </head> <body> <div id="container"> <div id="header"></div> <div id="content"></div> <div id="footer"></div> </div> </body> </html> 
+7
javascript sticky-footer
source share
4 answers

"DOMContentLoaded" The event is fired only if the document is ready, similar to jQuery $(document.ready) .

and for styles, you can use a class instead of setting each style using javascript.

the code

 document.addEventListener("DOMContentLoaded", function (event) { var element = document.getElementById('container'); var height = element.offsetHeight; if (height < screen.height) { document.getElementById("footer").classList.add('stikybottom'); } }, false); 
 #footer.stikybottom { position: fixed; bottom:0; left: 0; right:0; } 
 <div id="container"> <div id="header">header</div> <div id="content">Conent</div> <div id="footer">Something in footer</div> </div> 
+2
source share

I work very well. there may be no function call function.

 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"; } } KeepFoot(); 

see this jsfiddle

+2
source share

The function is not called at boot. You can attach the KeepFoot function directly to a body tag like this, instead of calling it this way:

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

or use my code 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"; } })(); 
+2
source share

If you want to keep the footer at the bottom of the page, you should read this. cssreset.com/how-to-keep-footer-at-bottom-of-page-with-css/

You can do it without js.

0
source share

All Articles