0

I have the following:

var element = $(this);
var divName = element.parents("div:eq(0)").attr("name");
$.each(boxInfo,function(i,n) {
    if( n.boxName == divName )
    {
        var newHeight = n.boxHeight;
    }
});

clicked.parents("div:eq(0)").animate({
    height: newHeight + 'px'
}, 1000);

Problem being "newHeight undefined". But if I do this:

var element = $(this);
var divName = element.parents("div:eq(0)").attr("name");
$.each(boxInfo,function(i,n) {
    if( n.boxName == divName )
    {
        alert(n.boxHeight);
        var newHeight = n.boxHeight;
    }
});

clicked.parents("div:eq(0)").animate({
    height: newHeight + 'px'
}, 1000);

it returns the height. How is it that 5 lines down the variable is undefined?

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Phil Jackson
  • 10,238
  • 23
  • 96
  • 130

2 Answers2

4

Your variable named newHeight is being declared inside of an anonymous function (the function that is passed as a parameter to $.each). This means that it's value is only available within that anonymous function. This concept is called scope. It explains why your variable is undefined outside of that anonymous function.

If you changed your code to declare the variable in a broader scope, your code would behave as you expected it. Observe:

var element = $(this);
var divName = element.parents("div:eq(0)").attr("name");
var newHeight;
$.each(boxInfo,function(i,n) {
    if( n.boxName == divName )
    {
        newHeight = n.boxHeight;
    }
});

clicked.parents("div:eq(0)").animate({
    height: newHeight + 'px'
}, 1000);
Community
  • 1
  • 1
Ken Browning
  • 28,693
  • 6
  • 56
  • 68
0

newheight's scope is limited to the anonymous function you're applyng to each boxinfo. you need to remove the var before newheight to make it a global.

also, your code isn't as efficient as it could be since you appear to be using each() to do something that jquery could do for you eg, $(boxInfo).find('[boxName=' + divName + ']')

Scott Evernden
  • 39,136
  • 15
  • 78
  • 84
  • what do you think jQuery does behind the scenes? At least with `.each` you can short-circuit the loop once you find it – nickf Oct 19 '09 at 10:22