proPhet
proPhet

Reputation: 1228

Get height of the div on window resize

I have a function that resizes divs depending on how high (in pixels) other divs with the same class are:

<script type="text/javascript">

    function resizeTheDivs(tag){
        // first get the tags to adjust
        var $tags = $('.' + tag);
        var $new_height = 0;
        // find out which one is largest
        $('.' + tag).each(function(){
            $(this).height() > $new_height ? $new_height = $(this).height() : null;
        });
        // make all others that height
        $tags.height($new_height);
        // I console.log($new_height) here sometimes
    }

    // resize divs on document load
    $(document).ready(function(){
        resizeTheDivs('the-class');
    });
    // resize divs on window resize
    $(window).resize(function () {
        resizeTheDivs('the-class');
    });

</script>

The divs resize correctly on page load, but when console.log($new_height) fires from the window resize function, the $new_height is not changed.

Context: There are 3 divs (floated left, so next to each other with 33% width) that contain text in p tags. So when I resize the browser width, the text gets 'longer', but the javascript function isn't picking up the new heights of the divs.

Any ideas?

Upvotes: 0

Views: 2512

Answers (1)

mch
mch

Reputation: 1279

You need to reset the height to auto before measuring it, or else it will always return the fixed value you set in $(document).ready:

function resizeTheDivs(tag){
    // first get the tags to adjust
    var $tags = $('.' + tag);
    var $new_height = 0;
    // find out which one is largest
    $('.' + tag).each(function(){
        $(this).removeAttr('style');
        $(this).height() > $new_height ? $new_height = $(this).height() : null;
    });
    // make all others that height
    $tags.height($new_height);
    // I console.log($new_height) here sometimes
}

Upvotes: 1

Related Questions