I am trying to identify the height of a div element in HTML, but I am not able to access the value outside of the function. This is the jQuery:
jQuery.noConflict();
(function($) {
$(function() {
$tmp_cont = $('<div></div>');
$tmp_cont.html($content);
$tmp_cont.hide();
$('body').append($tmp_cont);
var $height = $tmp_cont.height();
alert ($height);
});
})(jQuery);
alert ($height);
The first alert function works, but the second throws and error with $height
as undefined. How can I retain the value of $height
?
A scope is a region of the program and broadly speaking there are three places, where variables can be declared: Inside a function or a block which is called local variables, In the definition of function parameters which is called formal parameters. Outside of all functions which is called global variables.
You can't access variables declared inside a function from outside a function. The variable belongs to the function's scope only, not the global scope.
You need to declare the variable outside both functions, in a scope they can both access. I suggest combining your two document ready handlers into a single function and declaring the variable there: $(function() { var var1; // may want to assign a default $('a[id=1]'). live("click", function(event) { event.
JavaScript has global scope and local scope. Variables declared and initialized outside any function become global variables. Variables declared and initialized inside function becomes local variables to that function. Variables declared without var keyword inside any function becomes global variables automatically.
You can just remove the var
like this:
$height = $tmp_cont.height();
If you want a global variable, leave off the var
, or more explicitly:
window.$height = $tmp_cont.height();
Or if you still want it local, just declare it higher up, like this:
jQuery.noConflict();
var $height;
(function($) {
$(function() {
$tmp_cont = $('<div></div>');
$tmp_cont.html($content);
$tmp_cont.hide();
$('body').append($tmp_cont);
$height = $tmp_cont.height();
alert ($height);
});
})(jQuery);
alert ($height);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With