Reputation: 4214
I have an issue with two adjacent div "columns". It is a common use case that one of them might be gargantually taller than the other one, and this can be a usability issue, since users drag'n'drop items from one div to the other.
Using jQuery, I'd like to make sure that these two columns are always equal height. Not just on page load, but also if their inner content ever changes, or they're animated with jQuery or the page is resized or any other possible reason the height of taller div changes, the other one will follow.
What would be the fastest processing way of achieving this? (I'd like minimal lag on redraws on window resizing)
Thanks a lot in advance!
Upvotes: 2
Views: 1199
Reputation: 3721
<div class="same_height_kids"><div>foo></div><div>bar</div></div>
$('.same_height_kids').bind('DOMSubtreeModified change', function(e){
var min = 0;
$(e.currentTarget).children().each(function(i, e){
$(e).css({minHeight: 0});
if($(e).height() > min){
min = $(e).height();
}
});
$(e.currentTarget).css({minHeight: min});
$(e.currentTarget).children().each(function(i, e){
$(e).css({minHeight: min});
});
});
this is not tested code. the DOMSubtreeModified event is not supported be IE older then 9 nor by opera. as much as i know the onChange event works instead in some browsers. onResize usually only on windows and frames.
this implementation has the flaw that the divs can't get smaller. for that you have to remove the min-height before calculating the new height.
EDIT: updated code. example on http://jsfiddle.net/ADY3F/5/
Upvotes: 1
Reputation: 77348
You could bind to the resize
event on all matching divs then in the callback just set their heights = to each other. Here's a fiddle of the below:
$(document).on("resize", ".selector", function() {
var max = function(array){ return Math.max.apply(Math, array); }
var heights = $(".selector").map(function() { return $(this).height() }).get();
$(".selector").height(max(heights));
});
The handler above contains 3 steps:
Upvotes: 2
Reputation: 100170
If you don't need to support IE older than v8, then CSS can do it for you with display:table-cell
.
Upvotes: 0
Reputation: 6278
<html>
<head>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.7.1.js"></script>
<script type="text/javascript">
$(document).ready(function(){
setInterval(checkSizes, 1000);
});
$(window).resize(function(){
checkSizes();
});
function checkSizes(){
if($("#myDiv1").height() != $("#myDiv2").height()){
console.log("Sizes do not match");
alert("Sizes do not match");
}
}
</script>
</head>
<body>
<div id="myDiv1">
test
</div>
<div id="myDiv2">
test<br />
test
</div>
</body>
</html>
This example checks every second and checks every time the window is resized. If they do not match. It alerts you in both the message box and with the console.
With css, you can also set the maximum height of a div. It would clip any excess.
max-height:50px;
Upvotes: 0