I have this code:
function displayMenu (newGal, newSub) {
curGal = newGal;
curSub = newSub;
if (curGal == null) {
curGal = "main";
};
arrayL = curGal.length;
if (curImg == null) {
curImg = 0;
};
if (curSub == null) {
curSub = 0;
};
prevImg = curImg - 1;
if (prevImg == null || prevImg < 0) {
prevImg = arrayL;
};
nextImg = curImg + 1;
document.getElementById('img1').style.display = "none";
};
And no matter what it’s giving me that the style property is null. This code is massively torn down from what it used to be; this was part of a for loop that was supposed to use i to target "img" + i to select the divs with the id of img0–9, then I broke it down and tried manually targeting every single img0–9 with a separate line and it just keeps breaking. Yes, the img0–9 divs are in the HTML. The original for loop looked like this:
for (i = 0; i < array.L; i++) {
var tempButton = "img" + i;
document.getElementById(tempButton).style.display = "none";
};
Why is the style property null, and how can I fix it?
This is your problem. Use this instead:
In your code,
displayMenuis called and then the return value of that call is assigned towindow.onload. This fails, because you are assigningwindow.onloadbefore theimgXelements have been added.In the solution, you are instead assigning a function literal to
window.onloadwhich, when called, runsdisplayMenu. It now works because the elements have been placed on the page.