Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Variable Scope outside jQuery function

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?

like image 776
Atif Avatar asked Nov 11 '10 11:11

Atif


People also ask

What is the scope of a variable that is declared outside a function?

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.

Can we declare variable outside function?

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.

How pass local variable to another function in jquery?

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.

How do you use a variable outside a function in JavaScript?

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.


1 Answers

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);
like image 157
Nick Craver Avatar answered Oct 21 '22 17:10

Nick Craver