jquery - use a variable outside the function

37,691

Solution 1

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);
    });
});

Solution 2

try this

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

Solution 3

If you declare the variable outside the function, then assign a value to it inside the function, it should be accessible elsewhere. So long as you're sure that a value will be assigned. If you're not sure, you might want to 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);
    });
});
Share:
37,691
user705730
Author by

user705730

Updated on July 05, 2022

Comments

  • user705730
    user705730 almost 2 years

    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