0

How do you access the variable from an external JavaScript within a HTML page?

In my external JavaScript file(init.js), I created a variable call:

var myMessage="Hello World";

And in my HTML page which has init.js included but when I try alerting it:

alert(myMessage);

It gives me an error. Sample code here

Vincent1989
  • 1,525
  • 14
  • 22

2 Answers2

2

You can call external js variable through making

var init={
myMessage="Hello World";
}

call your html code

alert(init.myMessage);
orvi
  • 2,500
  • 1
  • 20
  • 34
Muhammad Waqas
  • 1,290
  • 12
  • 19
1

your codepen sample does not include the code as an external file but internally so that is an issue, but generally you need to wait for the page and all elements to finish loading.

The example bellow will wait 1000ms or 1sec and then you'll see that the alert will show the variable.

 <div>
 Body content
 </div>
 <script>
   setTimeout(function() {
   alert(myMessage);  
   },1000);
 </script>

The better way is of course to use jQuery's

    $('document').ready(function(){  });

instead of a timer as you can't be sure 1 second is enough. the connection might be poor and it could take more for all the pages to load.

If you dont want to use jQuery there are vanilla JS ways to do it as well.

pure JavaScript equivalent to jQuery's $.ready() how to call a function when the page/dom is ready for it

Community
  • 1
  • 1
Ekim
  • 1,085
  • 9
  • 26