views:

111

answers:

2

I have a sidebar on my page that I want to always be 100% of the container size. Sadly, I can't tell the element to do this via CSS alone as the page has a variable height due to dynamic content.

Is it possible to use jQuery to find the height of the content container, and adjust the sidebar height to match it?

I found a few jQuery plugins that kind of do what I want, but feel they are over complicated (and I can't seem to get them to work anyway!).

A: 

Assuming the id of your container is "container" and the id of your sidebar is "sidebar", you could try the following (untested!)

$(document).ready(function() {
    $('#sidebar').height($('#container').height());
});

This should (on document load), resize the sidebar height to the same as the container height.

Damovisa
Note if you have anything that resizes the page (perhaps with `slideDown`) you will need to call this code again.
alex
@alex: That's very true. Good point.
Damovisa
A: 

I'm going to continue on from Damovisa's answer.

$(document).resize(function(){
     $('#sidebar').height($('#container').height());
});

However, this could fire an awful lot if you resize the page a lot. You could try this

  $(document).resize(function(){         
        clearTimeout(resizeTimeout);
        resizeTimeout = setTimeout(function() {
            $('#sidebar').height($('#container').height());
        }, 100);
    });

In the second example, it will only resize 100 microseconds after resizing.

This is also assuming that $(document).resize() will be triggered when the page size changes. You could always wrap it in a function, and call it on completion of any slideDown() etc

alex
Pretty good solution. I guess the ideal solution really depends on what can change the size of the container.
Damovisa
Instead of listening to a document resize, why not bind to a window resize?
Matt Ball
I'm not sure if that means the user actually resizes the window frame, or the viewport changes from something growing taller. Guess I have to test it.
alex