Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jquery - use a variable outside the function

How I Can use a variable outside the function where it was declared?

$(function() {
    function init() {
        var bwr_w = $(window).width();
    }
    init();
    $('#button').click(function() {
        alert('The Browser Height is' + bwr_w);
    });
});

If I click on the button I get this error:

bwr_w is not defined

like image 526
user705730 Avatar asked Apr 13 '11 10:04

user705730


People also ask

Can you use a variable outside a function?

Variables declared outside of any function become global variables. Global variables can be accessed and modified from any function. In the above example, the variable userName becomes a global variable because it is declared outside of any function.

How do you use a variable outside of a function inside a function?

you have to declare the variable outside the function to use it. variables declared inside a function can only be accessed inside that function. think of each function as a box and the lid can only be opened from inside: the function can grab what's outside or put something out, but you can't reach in its box.

Can I use var outside function JavaScript?

Variables declared Globally (outside any function) have Global Scope. Global variables can be accessed from anywhere in a JavaScript program. Variables declared with var , let and const are quite similar when declared outside a block.

What is $scope in jQuery?

The scope is the binding part between the HTML (view) and the JavaScript (controller). The scope is an object with the available properties and methods. The scope is available for both the view and the controller. You have more detailed explanation here.


2 Answers

Just declare that variable in constructor's scope:

$(function() {
    var bwr_w = null;

    function init() {
        bwr_w = $(window).width();
    }

    init();

    $('#button').click(function() {
        alert('The Browser Height is' + bwr_w);
    });
});
like image 84
Matías Fidemraizer Avatar answered Oct 04 '22 22:10

Matías Fidemraizer


try this

$(function() {
  var bwr_w = 0;
  function init() {
    bwr_w = $(window).width();
  }
  init();
  $('#button').click(function() {
    alert('The Browser Height is' + bwr_w);
  });
});
like image 33
Andrei Andrushkevich Avatar answered Oct 04 '22 22:10

Andrei Andrushkevich