Leron
Leron

Reputation: 9866

jQuery function for setting equal heights on two divs

I was trying to implement my own function for equalizing the height of two divs but I got some strange behavior. Here is an example of what I'm doing at the moment - JSFiddle

I don't get this problem when I test it on my computer, but you can see in the fiddle example that when you minimize and then maximize the browser the final result is not what's the goals is.

The problem that I get on my computer is that when I hit F5 or resize it's working properly, but if I hit Ctrl + F5 the #vertical-menu gets shorter the the #vertical-content and if I press again F5 it's adjusted.

The problem with Ctrl + F5 seems like not a big deal but still I want to find a way to solve it. But now that I get this strange behavior in the Fiddle example I'm starting to think that maybe my function is not working properly.

So how can I fix my function to properly adjust the height every time. The problem with Ctrl + F5 is it connected with the function or it's more related to what exactly this key combination is doing and still - can I avoid the fact that my divs are not sized properly in this case? And is resizing with jQuery a good approach? When I was first looking for how people do this adjusting heights thing I saw something that seemed more like a hack to me with setting big negative margin like margin-bottom: -10000px and then big padding - padding-bottom: 10000px; but because I didn't fully understood the idea behind this and because I thought that JavaScript/Jquery would be the cleaner way I decided to go with jQuery function, but if I get too many H-cases is it better to use this hack instead of jQuery function?

Upvotes: 0

Views: 842

Answers (1)

Gerico
Gerico

Reputation: 5169

I couldn't see the refresh issues you're getting, however i did notice if you made the window smaller, then resized the window back to a larger viewport, the menu didn't shrink with the content. I found changing the jQuery slightly to this means it looks at both scenarios, where the menu is longer or shorter than the content:

http://jsfiddle.net/xchu5/2/

function calcHeight() {
    var contentHeight = $('#vertical-content').height();
    var menuHeight = $('#vertical-menu').height();
    var windowHeight = $(window).height();
    if (menuHeight < contentHeight) {
        $('#vertical-menu').css('height', contentHeight + 40 + 'px');
    }
    else if (menuHeight > contentHeight) {
        $('#vertical-menu').css('height', contentHeight + 40 + 'px');
    }
}
$(document).ready(calcHeight);
$(window).bind("resize",calcHeight);

Upvotes: 2

Related Questions