Jquery - use a variable outside the function

How can I 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 not defined

+4
source share
3 answers

Just declare this variable in the constructor area:

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

try it

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

If you declare a variable outside the function, then assign it a value inside the function, it should be available elsewhere. Until you are sure that a value will be assigned. If you are not sure, you can assign a default value:

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

Source: https://habr.com/ru/post/1347892/


All Articles