Stephen
Stephen

Reputation: 319

How to structure a JavaScript/HTML website for global variables?

I'm building a dynamic website that gives travel directions, but I'm new to JavaScript and I'm not sure of the best way to code it.

Currently, I'm loading different parts of the site (header, main, footer) by having separate HTML pages for each element, and then loading these pages into the main page. For example, on the main page I have:

<body onload="initialize()">
   <div id="header"></div>
   <div id="main"></div>
   <div id="footer"></div>
</body>

And in the imported JavaScript script I have:

function initialize() 
{
   $('#header').load('header.html');
   $('#main').load('main.html');
   $('#footer').load('footer.html');
}

The issue is that I want all three of these imported pages to have access to global variables and functions in a single JavaScript file where I will be storing route information, coordinates, etc. Specifically, I ran into problems where I was unable to call a function in my main JS script from the header.html page that had been loaded into the parent page.

What is the best way to do this? Any help is much appreciated!

Upvotes: 0

Views: 1499

Answers (3)

Dave Anderson
Dave Anderson

Reputation: 12294

You should have a single js file with all your client side code in and include that on the page with a <script> tag. Then employ $( document ).ready() to run your initialisation. You can also define global variables here and assign them so they can be accessed later.

In your JavaScript include will be something like this;

var $header, $main, $footer

function initialize() 
{
   $header.load('header.html');
   $main.load('main.html');
   $footer.load('footer.html');
}

$(document).ready(function() {
  $header = $('#header');
  $main = $('#main');
  $footer = $('#footer');

  initialize();
});

Be careful with the number of global variables you create though see; 11 JavaScript mistakes you're making.

Upvotes: 2

Pradip Kharbuja
Pradip Kharbuja

Reputation: 3542

in main page.

<script type="text/javascript">
    variable = <value>;   //variable used with var keyword is considered as global variable
</script>

Upvotes: 0

F25rT
F25rT

Reputation: 114

have you tried putting it outside on the function to make it global ...

var <variable name>
function <function_name>{

<variable name>

}

Upvotes: 0

Related Questions