Michael Peterson
Michael Peterson

Reputation: 1123

Dynamically change height of container div when content changes height

I have a website with different sections, each set to be the height of the browser window. In some cases, the content is taller than the browser window, and I use a function to check for this and set the height of the div to be the height of its content, using the function:

$('.container').each(function() {
        var _this = $(this);
        var this_ = this;
        var windowH = $(window).height();
        var textH = $('.text', this).height();
        if(windowH < textH) {                            
            $(this).css({'height': textH + 'px'});
        }
        else {
            $(this).css({'height': windowH + 'px'});
        }
        $(window).resize(function(){
            var windowH = $(window).height();
            var textH = $('.text', this_).height();
            if(windowH < textH) {
                _this.css({'height': textH + 'px'});
            }
            else {
                _this.css('height', windowH + 'px');
            }

        });         
    });

The issue I am having is that I want to dynamically hide and show content, and when the new content is taller than the current height of the div, I want the div to expand to contain it. I am using the function,

$('#container').on('click', 'p', function () {
    $(this).height('300px');
    var windowH = $(window).height();
    $('#container').css({
        'height': ($('#container .text').height() + 'px')
    });
    var textH = $('#container').height();
    if (windowH < textH) {
        $('#container').css({
            'height': textH + 'px'
        });
    } else {
        $('#container').css('height', windowH + 'px');
    }

});

but with no success. I have created a fiddle, http://jsfiddle.net/wDRzY/

Upvotes: 0

Views: 974

Answers (1)

Nick Bernhard
Nick Bernhard

Reputation: 106

Using a nested div, limit the height of the outer div and let the inner div stay the height of the content. When you need the outer div to be the height of the content, you can set the outer div height equal to the inner div height.

Although, I'm not sure why you would need to do this at all. I would suggest reading up on CSS more and using that for display purposes like this.

Upvotes: 1

Related Questions