Reputation: 9797
I want the footer be just below the window in the initial position and when I resize the window. I need to declare the var outside and again inside the function to make it work. Is it ok or there is a better way to do it?
$(function(){
// initial position:
var docHeight = $(window).height();
$('#footer').css('margin-top', docHeight + 'px');
// position when I resize the window:
$(window).resize(function() {
var docHeight = $(window).height();
$('#footer').css('margin-top', docHeight + 'px');
});
})
I have the code here to play: http://jsfiddle.net/dWpp5/
Upvotes: 2
Views: 591
Reputation: 506
JavaScript has "Function scope". So like you said if you define a variable with the "var" keyword it become local to whatever function block it is inside. Anything outside of that function cannot see it.
However if you don't use "var" to define a variable or use "var" but outside of a function - it is a global variable that any function or expression has access to.
The cool thing about function scoping is that while noting outside of that function can see the variable - any functions that are executed or defined inside of the parent function does.
The hole goes deep - if you use a variable in a function, and the function doesn't see it defined inside of itself, it goes to its parent to see if it's defined there. If it doesn't it find a definition - it goes to its parent's parent - and so on and so forth until it reaches the global scope - if it doesn't find a definition on the global scope the variable is declared in the global scope.
Here's a Smashing Magazine article on scoping.
Upvotes: 2
Reputation: 45155
This works just as well:
$(function(){
// initial position:
// this is a variable local to the doc ready function
var docHeight = $(window).height();
$('#footer').css('margin-top', docHeight + 'px');
// position when I resize the window:
$(window).resize(function() {
// since this function is contained within the outer function,
// the docHeight local from the outer scope is accessible here.
$('#footer').css('margin-top', docHeight + 'px');
});
})
// Here, however, docHeight is NOT accessible.
Upvotes: 1