HTML and CSS Reference
In-Depth Information
};
document.getElementById("Div2").onclick = function () {
};
document.getElementById("Div3").onclick = function () {
};
function AFunction() {
var x;
}
function BFunctionWithParam(p) {
}
}
</script>
</head>
<body>
<div id="Div1"></div>
<div id="Div2"></div>
<div id="Div3"></div>
</body>
</html>
In Listing 1-7, notice that the <script> block creates a section of script available to the
entire page. The first line in the script section is the variable globalVar , which is considered
global to the entire page. Any JavaScript anywhere on this page could access this variable. At
the next level, the code implements a window.onload event handler. Inside this event handler,
the first line declares a variable called localVar , which is local to the onload event handler.
Inside the onload event handler, the code has access to the globalVar variable.
Now things start to get interesting.
The onload event handler accesses the DOM to wire up some other event handlers.
Inside these event handlers, the code has access to both localVar and globalVar variables.
The localVar variable is local to the onload event, but because the other event handlers are
declared within the onload event handler, they also have access to local variables declared in
the onload event handler. Update the Div1 onclick handler to this code:
document.getElementById("Div1").onclick = function () {
var insideDiv1Click = "insideDiv1";
alert(globalvar);
alert(localVar);
alert(insideDiv1Click);
};
When this code runs and a user clicks the Div1 element, all three alerts successfully display
the value of each variable, which means they are all in scope.
Now, update the Div2 onclick handler with this code, the same as was placed into Div1 :
document.getElementById("Div2").onclick = function () {
alert(globalVar);
alert(localVar);
alert(insideDiv1Click);
};
Search WWH ::




Custom Search