javascript/jquery passing variables

10,535
<script type="text/javascript">
    window.$vars = {
        width: 300
    };
</script>

<script type="text/javascript">
    (function(){
        var k = window.$vars.width;
        alert(k);
    })();
</script>

Putting the variable in global scope will do it.

Share:
10,535
hellomello
Author by

hellomello

On the path to learning all things React Native at the moment. I'll be right back!

Updated on November 22, 2022

Comments

  • hellomello
    hellomello 12 months

    I was wondering if there is a way that I can pass variables like this:

    <script type="text/javascript">
    width = 300;
    </script>
    
    <script type="text/javascript">
    (function(){
        var k = width;
        alert(k);
    });
    </script>
    

    I'm trying to learn how I can pass width into the variable k. I dont want to do var width =300 Is there a way to do such a thing like this? so eventually I can place the bottom script, (function(){...}); into a file where I can just do this

    <script type="text/javascript">
    width = 300;
    
    //more variables if needed
    
    //height = 300;
    //name = "example";
    //...
    </script>
    
    <script type="text/javascript" src="thefile.js"></script>
    

    So I can add more variables if I have to

    Thanks!

    • coolguy
      coolguy over 11 years
      You can do that with the help of cookie
    • Jonathan Ong
      Jonathan Ong over 11 years
      what's wrong with your solution? the only difference is that I would only define a single object with all the required variables. and no, cookies are unnecessary.
    • woutr_be
      woutr_be over 11 years
      This should actually work, since the variable is declared before you include the other scripts, it should be available
    • chrisvillanueva
      chrisvillanueva over 11 years
      agree with @JonathanOng. it looks like you are trying to create one configuration file. i would put these configuration settings in on object. i would then define variables with select object values.
    • gilly3
      gilly3 over 11 years
      The code you have works as is - or it would except that the code in the bottom script never gets executed. You need to add a trailing () before the semicolon to invoke your function.