When I run the following script, console reports an error in the last line saying that “colors” is not defined. I thought I defined it (an array) at the beginning of the script, so why is it not defined at the end while still in the script?
<script>
(function sampleArray() {
"use strict";
var colors = [],
form = document.getElementById('formColor');
form.addEventListener("submit", function(e) {
e.preventDefault(); // prevents the form from submitting
var newColor = formColor.newColorInput.value;
colors.push(newColor);
console.log ("new color = " + newColor);
console.log (colors.join(', '));
}, false);
})();
// colors is not defined:
document.getElementById('arrayStuff').innerHTML += "<em>Colors = " + colors.join(", ") + "</em>";
</script>
</body>
It looks like if I moved the var colors =, and the next line to before the function, it becomes global, and the error goes away. However, I still don’t see the div innerHTML being populated.
<script>
(function sampleArray() {
"use strict";
var colors = [],
form = document.getElementById('formColor');
form.addEventListener("submit", function(e) {
e.preventDefault(); // prevents the form from submitting
var newColor = formColor.newColorInput.value;
colors.push(newColor);
console.log ("new color = " + newColor);
console.log (colors.join(', '));
}, false);
})();
[b]// END OF FUNCTION - NOTHING DEFINED IN THE FUNCTION EXISTS ANY MORE[/b]
// colors is not defined:
document.getElementById('arrayStuff').innerHTML += "<em>Colors = " + colors.join(", ") + "</em>";
</script>
</body>
May be you need to move the assignment inside the function
I put it right after “}, false);” and it did not work. I put it before that and now it works!
Thanks for your direction!