Extend a <div> element to the bottom of the page with Javascript
This is the situation: You have some kind of footer markup on your page and you want it (probably the background of it, actually) to extend to the bottom of your browser window. Your site is dynamic so it usually does so automatically, but on short pages, it stops abruptly and looks odd. This post proposes a solution.
There are only a few things you need to know:
• Height of the page in pixels (not browser window visible area, but the entire scrolling length). • Position of the top of the <div> you wish to extend.
You need to know how to use Javascript to obtain these values, and how to use it to set the height of the <div> element you want to extend. This is pretty basic Javascript stuff. First let’s look at a function you’ll put in your page <head>.
function extend_bottom()
{
var e = document.getElementById('element_to_extend')
var tmp = e
var o = e.offsetTop
while (tmp.parentNode.tagName != "BODY") {
if (tmp.parentNode.tagName == "DIV") {
o = o + tmp.parentNode.offsetTop
}
tmp = tmp.parentNode
}
var h = window.innerHeight - o
e.style.height = "" + h + "px"
}
That is almost entirely all you need. We gave the element to extend the ID ‘element_to_extend’ (ie, <div … id=”element_to_extend” …>… The code grabs a reference to the element, traverses up the node hierarchy to each parent element that has “DIV” as a tagName, and adds the element.offsetTop of each to a variable, o. The height of the element needed is now easily calculated by ‘window.innerHeight – o’. The last line in the function sets the height value in the elements style which ultimately is what does the job.
There is just one more thing you need to do: call this function. The way I’ve done it is to use the <body> ‘onload’ callback. Your <body> tag should look like this:
<body onload="extend_bottom()">
That’s all there is to it. To see it in action, go to this (non-existant) page and notice that the translucent footer extends to the bottom of the page. It should go to exactly the bottom of the page, unless your browser window is very short, so there should be no scrollbar on the right hand side of the page.
Note: updated slightly after original post with a better way to find pixel top of element to extend. Instead of going up parents while the parent is a <div>, we go all the way up to the <body> tag, adding only offsetTop of <div> elements.



