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?
window.onloaddoes?().window.onload = positioncompare withposition(). Extracting the definition ofpositioneliminates the duplication and a potential source of "differences" for an "identical" function. Once this is done it can be safely argued for that the execution context is what matters or if something else is amiss. (Also, I recommend using local variables to avoid contamination.)()'s