Within the global scope (aka "window"), variables are global.
Check this out:
//this is global because it is in the global scope (the window)
var foo = 'stuff';
//because it is global (window) you can also access it like this:
console.log(window.foo); //'stuff'
Now you can access foo
anywhere. It's worth noting that globals aren't best practice - so check out Object Oriented Programming (SOLID principles).
If you are within another scope (like a function) and don't use the var
keyword to create a variable, the variable will be global:
function someFunction() {
someVariable = 'stuff'; //this created a global variable! (or references an existing one)
//you could also assign it to window:
window.someVariable = 'stuff';
//both are the same thing!
}
Inline js (onclick in your html) is not a good practice. Instead, you can follow the good practice and use javascript to register the click event:
//get reference to button
var myBtn = document.getElementById('myBtn');
//add click function
myBtn.addEventListener('click', function(event) {
myFunction();
});
function myFunction() {
console.log(foo); //'stuff'
}
Here's a demo of all of this: http://jsbin.com/OmUBECaw/1/edit
Just note that you'll need to get the element references after they are loaded into the dom. It's best practice to include your scripts just before the end of the body rather than in the head, like this:
<!-- scripts here! -->
<script></script>
</body>
If you must keep the scripts in the head
, then you'll need to put your javascript code in a function to run onload of the window:
window.addEventListener('load', function() {
//code here!
});