joomla3 javascript document.getElementById().style doesn't work

481 Views Asked by At

This code in index.html (no joomla):

<script>
    var left  = document.getElementById('zijmenu').offsetHeight;
    var right = document.getElementById('container').offsetHeight;
    document.write("hoogte linkerkant: ", left, " hoogte rechterkant: ", right);
    if (left < right)
       {document.getElementById('zijmenu').style.height = right;}
    else 
       {document.getElementById('container').style.height = left;}
</script>

works fine:

<div id="zijmenu" style="height: 232px;">

when I add the same script in the index.php of the template in Joomla 3.3 the result is:

<div id="zijmenu" style="">

document.write works as expected: hoogte linkerkant: 132 hoogte rechterkant: 232

Why doesn't it pick up the style? I can't seem to find the answer anywhere....

Help is appreciated!

Regards Lenneke

1

There are 1 best solutions below

1
On

Units are required when setting styles with plain javascript, and offsetHeight returns a rounded integer, so you probably need to do

document.getElementById('zijmenu').style.height = right + 'px';

Note that the offsetHeight only returns the correct value when all the elements are loaded, which could be an issue with images etc. and that you can only get an element by ID once it's available in the DOM, so the script should come after the elements.

As a sidenote document.write is not recommended as it overwrites the document if called after the document has loaded.