I would like to assign document elements to global variables so that I am able to use these elements everywhere in my code.
My code:
// document elements
var drop = null;
var status = null;
var show = null;
function process (drop, status, show) {
if (document.readyState == 'complete') {
// init elements
drop = document.getElementById(drop);
status = document.getElementById(status);
show = document.getElementById(show);
}
// init event handlers
drop.addEventListener('drop', handleDrop, false);
}
function handleDrop (evt) {
// do something
}
The problem is I can’t do anything with the document elements using the global variables in the function handleDrop while in the function process everything works as it should…
EDIT: For example, I can read the content of the element show (show.innerHTML) in the function process but not in the function handleDrop.
The problem is that all these
drop,status… variables withinprocessfunction are the local ones – they refer to its arguments, and not the variables defined earlier.If these were defined at the outer-most level (i.e., not within any function’s body), you can access (and alter) them like this:
But I’d actually suggest another way: using separate names for params and ‘closured-over’ variables. Like this:
Both ways allow you to address these variables within
handleDropfunction; the latter one is obviously superior, because you are not restricted with what scope to choose.