PepeHands
PepeHands

Reputation: 1406

using variables from another js

Suppose I have some html file and it's have some script inside it. Then, I need to use another one script and want to use some variable from previous one. How Can I do it? Example:

<body>
    <script>
        var a = 1;
    </script>
    <p id="p"></p>
    <script>
        document.getElementById("p").innerHTML = a;
    </script>
</body>

Its says that "a" is undefined.

Upvotes: 0

Views: 44

Answers (2)

Fizer Khan
Fizer Khan

Reputation: 92735

Yes, you can do it. Your code works without any error. If you declare a variable inside the script tag directly, it comes under global scope which can be accessible from anywhere. But that script must be included before script which uses the variables.

Better you can define your namespace and use that. Otherwise your global variable most likely clash with other script's variable. It will be painful to debug.

  var myNamespace = {};
  myNamespace.a = 2;

In other scripts, use it like myNamespace.a.

Upvotes: 2

Pothys Ravichandran
Pothys Ravichandran

Reputation: 345

Just Put all Script codes inside a Head tag

<head>
    <script>
        var a = 1;
    </script>

    <script>
        document.getElementById("p").innerHTML = a;
    </script>
</head> 
<body>
    <p id="p"></p>
</body>

Upvotes: 0

Related Questions