I want another function (or several functions) to use the result of the first move function, that is, to show what the variable w is equal to at the moment.

Here is an example:

 function move() { var w = document.documentElement.clientWidth } $(window).resize(move); $('.button').click(function() { alert(w); }) 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script> <div class="button">Узнать ширину</div> 

in the example, the function does not work on click, as the variable w not found

    1 answer 1

    If simple, use the global scope:

     var w = document.documentElement.clientWidth; // первая инициализация function move() { w = document.documentElement.clientWidth } $(window).resize(move); $('.button').click(function() { alert(w); }) 

    And you can also:

     function move() { move.w = document.documentElement.clientWidth } $(window).resize(move); $('.button').click(function() { alert(move.w); }) 

    Although almost nothing differs from the previous example, the move should still be visible in the scope of the click handler.

    • in the first variant, as I understand it, the width of the document is entered into the variable w, when the window is resized, a function will work that will calculate this width again, but by clicking, the alert will still get the width that was calculated initially before the change (window width) or I’m wrong ? - Yevgeny Shevtsov
    • @ YevgenyShevtsov, you are slightly mistaken, in our case w is a global variable, if we in the function call it without the keyword var , then we work with the global one, therefore assigning to it a value, our global w changes. Your example did not work, because you created your local w , which is not visible outside the f- move function - hence the error - ThisMan
    • I'm starting to understand something, my code will be significantly reduced now, otherwise I’m covered with wrappers)) - Evgeny Shevtsov
    • @YevgeniyShevtsov, read about область видимости in javascript , this is a very cool thing - ThisMan