0

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.

3
  • What line is it saying that itemHeight is undefined? Commented Mar 7, 2015 at 22:31
  • And what is the output of the console.log? Commented Mar 7, 2015 at 22:33
  • The console output is '44 > undefined' Commented Mar 7, 2015 at 22:34

1 Answer 1

1

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;
}
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks for that, it is very obvious now I have the answer, facepalm. Though now the console is outputting '22 > 0, 44 > 22, 44 > 0'
@Forxs: That looks correct if you have two iterations in the outer loop. What result did you expect?
Ignore that, it's just poor logic now - the variable needs to be set before the previous .each. Thanks for your help

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.