Search code examples
javascriptjqueryhtmlvariablescall

Call variable from another script in HTML


I currently have a HTML file that has one script that is declared as follows:

<script src="//ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
  <script type="text/javascript">                         
 $(document).ready(function() {                           
    code.......
    var a = "hello"
});                                             
  </script>              

I am trying to add another script within the HTML file that will call on this variable "a". Right now, I am doing something like this:

<script type="text/javascript">                               
    alert(a);                                                              
</script>

But it is not alerting anything. If I replace a with a string like "hello", I do get alerted. Am I calling the variable wrong? I've tried searching for solutions but all of them say you should be able to easily call variables from another script assuming that script is declared and initialized before. Thanks.


Solution

  • Move the a declaration outside of the function.

    E.g.,

    var a;
    
    $(document).ready(function() {                           
        code.......
        a = "hello"
    }); 
    

    And then later on...

    alert(a);
    

    Remember that variables are function-scoped, so if you define it inside of a function, it won't be visible outside of the function.


    Update based on comments:

    Because you now have a timing issue when trying to interact with the a variable, I would recommend introducing an event-bus (or some other mechanism) to coordinate on timing. Given that you're already using jQuery, you can create a simple bus as follows:

    var bus = $({});
    
    bus.on('some-event', function() {});
    bus.trigger('some-event', ...);
    

    This actually lends itself to some better code organization, too, since now you really only need the bus to be global, and you can pass data around in events, rather than a bunch of other random variables.

    E.g.,

    var bus = $({});
    
    $(document).ready(function() {                           
        var a = 'hello';
        bus.trigger('some-event', { a: a });
    }); 
    

    And then in your other file:

    bus.on('some-event', function(e, data) {
        alert(data.a);
    });
    

    JSBin example (obviously not spread across multiple files, but the same principles apply).