Reputation: 785
I have multiple (potentially unlimited) "absolute" classes of DIFFERENT heights, but the below code sets EACH "relative" div to the height of the first absolute element. Each absolute div will be a different height, so I need to loop through and set each relative div to the height of its absolute div correctly.
HTML
<div class="relative">
<div class="absolute">
<p>content here, which will be variable, so the heights will not always be the same</p>
</div>
</div>
Jquery:
$( document ).ready(function() {
var current_height = 0;
$('.absolute').each(function() {
current_height = $('.absolute').height();
});
$('.relative').each(function() {
$('.relative').height(current_height);
});
});
CSS:
#relative {
position: relative;
display: block;
width: 100%;
}
#absolute {
position: absolute;
display: block;
overflow:hidden;
}
#relative,
#absolute {
width: 100%;
max-width: 820px;
}
Upvotes: 1
Views: 83
Reputation: 42054
My proposal is to use the jQuery function height instead of each:
$(function () {
$('.relative').height(function(index, height) {
//(this.querySelectorAll('.absolute')[0]).setAttribute('style','height:' + height + 'px');
// or in jQuery
$(this).find('.absolute').css('height', height + 'px');
});
});
#relative {
position: relative;
display: block;
width: 100%;
}
#absolute {
position: absolute;
display: block;
overflow:hidden;
}
#relative,
#absolute {
width: 100%;
max-width: 820px;
}
<script src="http://code.jquery.com/jquery-1.11.3.js"></script>
<div class="relative">
<div class="absolute">
<p>content here, which will be variable, so the heights will not always be the same</p>
</div>
</div>
<div class="relative">
<div class="absolute">
<p>content here, which will be variable, so the heights will not always be the same</p>
</div>
</div>
<div class="relative">
<div class="absolute">
<p>content here, which will be variable, so the heights will not always be the same</p>
</div>
</div>
<div class="relative">
<div class="absolute">
<p>content here, which will be variable, so the heights will not always be the same</p>
</div>
</div>
Upvotes: 0
Reputation: 803
The current_height
variable defined outside the first .each()
function gets overwritten with each iteration. You need just one loop and can nix the second .each()
function, like this:
$('.absolute').each(function() {
current_height = $(this).height();
$(this).parent().height(current_height);
});
Upvotes: 1