Reputation: 227
I've created a function that loops through a set of products, and sets the height of their copy area to the height of the tallest copy area in that set.
Here's my code:
function productCopyHeight(){
//make sub range product text sections the same height
if($('.sub-range').length){
$('.sub-range').each(function(){
var itemHeight = 0;
$(this).children('.product-item').children('.copy').each(function(i){
var thisItemHeight = $(this).height();
console.log(thisItemHeight + ' > ' + itemHeight)
if(thisItemHeight > itemHeight){
var itemHeight = thisItemHeight;
}
});
$(this).children('.product-item').children('.copy').css('height', itemHeight);
})
}
}
When I log it it shows the itemHeight variable as undefined when it is defined before the each loop.
Upvotes: 0
Views: 32
Reputation: 700302
That's because you are declaring another variable by the same name inside the callback for the inner each
. Here:
if(thisItemHeight > itemHeight){
var itemHeight = thisItemHeight;
}
That variable is different from the variable before the loop, and that variable is also hoisted to the top of the function. The variable has the value undefined
because you use it before you assign a value to it.
You should use the variable that you already have instead of creating another one:
if(thisItemHeight > itemHeight){
itemHeight = thisItemHeight;
}
Upvotes: 1