views:

27

answers:

2

I have a div, the container and few other divs inside - the layers. Visibility of layers is switched dynamically with JavaScript.

I want the container to fit its height to visible layer when switching between them, but also when we are zooming the page in or out. Generally I want to create a page that instantly loads all of its contents and chooses dynamically what is show, so maybe this can be done another way?

My approach was to put one layer on another by positioning them "absolute", but with this positioning the container doesn't fit its height any more. So I tried changing the height with JavaScript when switching layers (leaving support for zooming) but it seems not working, the height is still the same (minimal):

function selectLayer(layer_id) { var objs = document.getElementsByClassName("content-layer"); for (var i = 0; i < objs.length; i++) { if (objs[i].id == layer_id) { objs[i].style.visibility = "visible";

/* no reaction after executing line below */
objs[i].parentNode.height = objs[i].height + 20; // <---

} else { objs[i].style.visibility = "hidden"; } } } How to achieve full goal? Or at least, what's wrong with my code?

The rest of code, HTML:

... some content ... ... some content ... ... some content ...

CSS:

#contents { position: relative; z-index: 100; min-height: 350px; margin-left: 120px; border-width: 8px; padding: 0 0.75em; }

.content-layer { position: absolute; visibility: hidden; }

FF 3.6

A: 

Try using objs[i].offsetHeight instead of objs[i].height

Robusto
The problem is not in calculating the height. Even giving huge value the height is still the same.
adf88
+2  A: 

You are using the wrong property to get and set the height of your div. Try these:

var height = objs[i].offsetHeight //Get height

objs[i].parentNode.style.height = (height+20) + 'px'; //Set height 

And if you want to hide several divs and only show one at a time, you do not need to fudge with absolute positioning and Javascript pixel pushing. Just set the style display: none; to every div you want hidden and display: block; to the visible element. visibility: hidden hides an element from being drawn on screen but still allows it to take up space. display: none; on the other hand removes all visual traces of an element.

Example, take a 500px high image with a caption below it. Set visibility: hidden; to it and it will disappear, but the caption will still be in the same spot, below where the image used to be. Now set display: none; to it and the caption will move to where the top of the picture used to be, about 500px up. In other words, the containing element will generally automatically adjust to the height of elements inside it that take up space.

MooGoo