Reputation: 3801
I have a script that searches through some divs on a page, finds the tallest one and sets each div to that height, though i've come unstuck trying to run this function on a row by row basis. I have tried to add an each
function per row but to no avail, currently every div gets changed to the tallest of them all.
<div class="items-row">
<div class="span4"><p>Hello</p></div>
<div class="span4"><p>Hello</p></div>
<div class="span4"><p>Hello</p></div>
</div>
<div class="items-row">
<div class="span4"><p>Hello</p></div>
<div class="span4"><p>Hello</p></div>
<div class="span4"><p>Hello</p></div>
</div>
With the jQuery as follows
$('.items-row').each(function(){
var h = 0;
$('.items-row .span4').each(function(){
if (h < $(this).height()){
h = $(this).height();
}
});
$('.items-row .span4').each(function () {
$(this).css("height", h + 'px');
});
});
Im 50% of the way there, any help would be greatly appreciated.
The fiddle runs off a button click and the css is for text purposes only.
EDIT
Removed unused classed from the html that were for test purposes only.
Upvotes: 0
Views: 1428
Reputation: 3765
Give your .span4
selectors some context by using the this
keyword in your each loops. At the moment, you are setting the height of all of them to the tallest overall.
$('button').click(function () {
$('.items-row').each(function () {
var h = 0;
$('.span4', this).each(function () {
if (h < $(this).height()) {
h = $(this).height();
}
});
$('.span4', this).each(function () {
$(this).css("height", h + 'px');
});
});
});
Upvotes: 1
Reputation: 318162
The issue is that inside the loop, you're accessing all the elements with $('.items-row .span4')
, you need to access only the ones relevant for the current iteration with either find()
or $('.span4', this)
$('button').click(function () {
$('.items-row').each(function () {
$('.span4', this).css('height',
Math.max.apply( Math,
$.map($('.span4', this), function(x) {
return $(x).height();
})
)
);
});
});
Upvotes: 0
Reputation: 1483
Try the following
Demo: jsFiddle
$('button').click(function(){
$('.items-row').each(function(){
var h = 0;
$(this).find('.span4').each(function(){
if (h < $(this).height()){
h = $(this).height();
}
});
$(this).find('.span4').each(function () {
$(this).css("height", h + 'px');
});
});
});
Upvotes: 0