Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery height() not changing on resize

I never had this problem before but I can't seem to find the solution, so I hope you guys can help me out.

jQuery

function setTheHeight() {

    if( $('#main.level1 .block.attention .block-content').length ) {
        //Get value of highest element
        var maxHeight = Math.max.apply(Math, $('#main.level1 .block.attention .block-content').map (
            function() {
                return $(this).height();
            }
        ));
        console.log(maxHeight);
        $('#main.level1 .block.attention .block-content').height(maxHeight);
    }
}

setTheHeight();

$(window).resize(function() {
    setTheHeight();
});

Basicly what this function does is check for the highest div and set the height of all selected div's to this height. This works fine. BUT it's a responsive design so when the user resize's his browser the content gets smaller and the div higher. So i added a resize event. The event is being fired but it's not changing the height. Any idea's why the resize is not changing the height?

Quick jsFiddle to show what happens: http://jsfiddle.net/3mVkn/

FIX

Hmm this was just plain stupid. Because I was setting the height() it was already fixed so all I had to do is just reset the height and it worked.

Updated code:

function setTheHeight() {

    if( $('#main.level1 .block.attention .block-content').length ) {

        //Reset height
        $('#main.level1 .block.attention .block-content').height('auto');

        //Get value of highest element
        var maxHeight = Math.max.apply(Math, $('#main.level1 .block.attention .block-content').map (
            function() {
                return $(this).height();
            }
        ));
        console.log(maxHeight);
        $('#main.level1 .block.attention .block-content').height(maxHeight);
    }
}

setTheHeight();

$(window).resize(function() {
    setTheHeight();
});
like image 351
Sjors Avatar asked Jul 19 '12 11:07

Sjors


1 Answers

This is not jQuery related but CSS. It is because once you have set the height of the .block-content to some value, after you resize the window the heights of those .block-content wont change because the heights are no longer set to auto but to some predefined value.

The solution is to use return $(this)[0].scrollHeight instead of return $(this).height() This way it will return the real height of the content, not the CSS defined height.

EDIT:

The solution is actually to calculate the height of all children inside the .block-content and then return that value. I've edited your code here http://jsfiddle.net/3mVkn/12/

This should give you the result needed.

like image 101
Denis Pshenov Avatar answered Oct 17 '22 04:10

Denis Pshenov