Variable scope and variables crossing functions

Second question of the day :slight_smile:

I am using Ben Alman’s JQuery resize plugin in order to obtain the varying computed width of an element when the window is resized (the element in question is a page wrapper that exhibits the expand-to-fit behavior of a block box, and it’s computed width is obviously influenced by the resizing of the window.

Essentially, what I need to be able to do, is to reference a variable that is defined in a .resize() function (‘width_page’) in a seperate .each() function.


function foo(){
	
  $("#page").resize(function(){ var width_page = $(this).width() });

  $("#foo li div").each(function(){
    if (width_parent == '200'){
          $(this).css({'right':'0'});
    }
  });

}

I now understand that variables can’t cross boundaries like in the example above, which leaves me a little stuck. I also understand that this is specific to the context of the .resize() function, and that it can’t be taken out of it without using an element selector.

Is there some way I can call the .resize() function in my .each() function?

Thanks for the help in advance

For starters you have width_page and width_parent, I presume they’re supposed to be the same?

You can cross boundaries just fine by assigning to a variable that’s at a higher scope.

For example:


function foo(){

  var width_page;	

  $("#page").resize(function(){ width_page = $(this).width() });

  $("#foo li div").each(function(){
    if (width_page == '200'){
          $(this).css({'right':'0'});
    }
  });
}

Thanks for the reply, Paul.

In the end I managed to bypass using the resize plugin, as the computed width of the page wrapper is now obtained on hover (this script is going to be used in conjunction with a menu), which obviously takes into account any subsequent window resizing after the initial page load, before the menu item is displayed.

In terms of performance, is it advisable to define any variables - such as obtaining element widths, and subsequent calculations - outside of the .hover() event handler, or does it not make any difference?

They are in fact, different. I just failed to include the value of the other :slight_smile:

So by declaring a valueless variable at the ‘root-level’ of the function, it means that this variable can now cross function boundaries?

Really appreciate the help so far.

There is always access to variables that have been defined at a higher scope.

There’s a really good explanation of this at Identifier Resolution, Execution Contexts and Scope Chains