Jason
Jason

Reputation: 542

Need help setting div in table height using Javascript

I am trying to set the div to a certain height inside an empty table cell to set the cell to 100% height. (The whole page consists of just the table with no padding.)

Here is some relevant code:

<table border="0" width="100%">
 <tr>
  <td class="boxmiddleleft"></td>
  <td class="boxmiddlecenter"><script language="javascript" src="includes/clock.js">/*clock*/</script></td>
 </tr>
 <tr>
  <td class="boxbottomleft"><script language="javascript" src="includes/windowsize.js"></script><div id="divbottomresize"></div></td>
  <td class="boxbottomcenter"><button type="button" onclick="resizeheight();">Changed the window height? Reset by pressing this button.</button></td>
 </tr>
</table>

(With the div im trying to change height called '#divbottomresize')

And the JavaScript I am using for this:

var element = "divbottomresize";
function resizeheight(element) {
 var height = 0;
 var body = window.document.body;
 if (window.innerHeight) {
  height = window.innerHeight;
 } else if (body.parentElement.clientHeight) {
  height = body.parentElement.clientHeight;
 } else if (body && body.clientHeight) {
  height = body.clientHeight;
 }
 element.style.height =   ((height - element.offsetTop) + "px");
}

If you have any idea what I am doing wrong please could you tell me. Alternatively if you find other code that does what I want feel free to paste or link me. (I do not want to use jQuery if possible.)

When I run the code in Chrome and go to 'Inspect Element' I get the error:

windowsize.js:12Uncaught TypeError: Cannot read property 'style' of undefined on the line element.style.height = ((height - element.offsetTop) + "px");

EDIT: I have changed var element = "divbottomresize"; to var element = document.getElementById("divbottomresize"); as someone helpfully suggested. This still does not work and I get the same error and no height change.

Upvotes: 1

Views: 3100

Answers (1)

Stelian Matei
Stelian Matei

Reputation: 11623

The resize function requires the element parameter, so we need to update the HTML:

 <td class="boxbottomcenter"><button type="button" onclick="resizeheight('divbottomresize');">Changed the window height? Reset by pressing this button.</button></td>

Now, we need to change the Javascript, to use the STRING value passed by the function and then retrieve the tag with that ID for further processing:

function resizeheight(id_element) {
 var div = document.getElementById(id_element);

 var height = 0;
 var body = window.document.body;
 if (window.innerHeight) {
  height = window.innerHeight;
 } else if (body.parentElement.clientHeight) {
  height = body.parentElement.clientHeight;
 } else if (body && body.clientHeight) {
  height = body.clientHeight;
 }
 div.style.height =   ((height - div.offsetTop) + "px");
}

Upvotes: 2

Related Questions