I have a javascript function that dynamically positions a background image:
window.onload = function() {
bw = document.getElementsByClassName("BottomWrapper");
if (bw.length===0){
bw = document.getElementsByClassName("BottomWrapper2");
}
pos = window.innerWidth/2 - 490.5;
bw=Array.prototype.slice.call(bw);
bw[0].style.backgroundPosition="center 0px, " + pos + "px 0px";
};
and it works. But if I name the same exact function and run it:
function position() {
bw = document.getElementsByClassName("BottomWrapper");
if (bw.length===0){
bw = document.getElementsByClassName("BottomWrapper2");
}
pos = window.innerWidth/2 - 490.5;
bw=Array.prototype.slice.call(bw);
bw[0].style.backgroundPosition="center 0px, " + pos + "px 0px";
};
position();
I get the error:
TypeError: Cannot read property 'style' of undefined
I’m mystified. Why does the first function work and not the second?
if bw[0] is undefined, that means that document.getElementsByClassName(“BottomWrapper2”) returned undefined, which most likely means that the div was not on the page when the script was ran. If you load your code after your tag, this shouldn’t happen.
The reason the first would work is because it is waiting for the onload event to fire.