Search code examples
jqueryvariablesresizeglobal-variablesargument-passing

How can pass Jquery global variable to arguments in a function?


I want change table width when window going to resize, as I need to pass my global variable to a function as argument, but when I pass variables its not working and can't use variable in the method, how can I fix that, thanks for your help.

var WOS = document.body.parentNode.clientWidth; 
var HOS = document.body.parentNode.clientHeight;
$(window).resize(function(){    
   tableSetup(WOS, HOS);
}

function tableSetup(WOS, HOS) {
   alert(WOS); // give undefined message 
}

Solution

  • Since you want to get the updated values on resize, you need to calculate teh values in the resize event

    var WOS = document.body.parentNode.clientWidth;
    var HOS = document.body.parentNode.clientHeight;
    $(window).resize(function() {
      WOS = document.body.parentNode.clientWidth;
      HOS = document.body.parentNode.clientHeight;
      tableSetup(WOS, HOS);
    })
    
    function tableSetup(WOS, HOS) {
      snippet.log(WOS); // give undefined message 
    }
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
    <!-- Provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->
    <script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>

    Demo: Fiddle