I am trying to understand why a piece of code that I wrote doesn't work. (FYI, this is for a class, but I have already completed the project successfully, and now I am just trying to understand why something didn't work.)
I need to generate a picture x number of times and then append all of the pictures to a div.
Here is the HTML.
<body>
<div id="leftSide"></div>
<div id="rightSide"></div>
</body>
Here is the Javascript.
<script>
var theLeftSide = document.getElementById("leftSide");
var myVariable = 5;
function myFunction() {
for (var i = 0; i < myVariable; i++) {
var x = document.createElement("img");
x.setAttribute("src", "myFile.png");
x.style.top = Math.floor(Math.random() * 400) + "px";
x.style.left = Math.floor(Math.random() * 400) + "px";
theLeftSide.appendChild(x);
}
}
</script>
When I run the code, I receive a console message stating "Cannot read property 'appendChild' of null". When I move var theLeftSide inside the function, it works as expected.
I am new to JavaScript, but I thought that a variable declared outside a function using the var name = value; syntax would be considered global and therefore accessible inside a function?
I'm sure I am missing something but I'm not sure what.
Thanks!