views:

134

answers:

3
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"&gt;
<html xmlns="http://www.w3.org/1999/xhtml"&gt;
<HEAD>
<script type="text/javascript" src="lb-core.js"></script>
<script type="application/javascript">
var lbp = {
    defaults: {
        color: "blue"
    },
    init: function(config) {
        if(config) {
            for(prop in config){
                setBgcolor.defaults[prop] = config[prop];
            }
        }
        var bod = document.body;
        bod.style.backgroundColor = setBgcolor.defaults.color;
    }
}
window.onload = lbp.init();
</script>
</HEAD>
<body>
<div id="container">test</div>
</body>
</HTML>

Why does bod come back as undefined when the above is called at window.onload?

+1  A: 

Try this:

var bod = document.body;

I don't know why bod comes back as undefined in your code.. it works for me in Chrome. What browser are you running?

Also, are you sure it's bod that's undefined? Not setBgcolor or something else?

EDIT:

Change this line of code:

window.onload = lbp.init();

To this:

window.onload = lbp.init;

You're currently assigning the result of lpd.init() to onload.. you need to just assign the reference.

Matt
Added full page code. Running in firefox.
Matrym
@Martym See my edit
Matt
Thanks Matt - right on the money.
Matrym
+2  A: 

Change it to

window.onload = lbp.init;

When you write window.onload = lbp.init(), you are calling the init function, and assigning whatever it returns to window.onload.
Therefore, the function is being called immediately (before the window is loaded), and you're assigning undefined to window.onload. (Because init doesn't return anything)

You need to assign the init function itself to onload without calling it.

SLaks
Thanks, you're right slaks :)
Matrym
+2  A: 

Your code needs a few teaks, here's an overall fix:

var lbp = {
    defaults: {
        color: "blue"
    },
    init: function(config) {
        if(config) {
            for(prop in config){
                lbp.defaults[prop] = config[prop];
            }
        }
        var bod = document.body;
        bod.style.backgroundColor = lbp.defaults.color;
    }
}
window.onload = lbp.init;

Previous it was calling init instantly because window.onload = lbp.init() was assigning the result of lbp.init to the onload function, not assigning the actual function, this is fixed above.

Also, not sure where setBgcolor comes from in your code, I believe you meant lbp here, it works in the same code above, give it a test.

Nick Craver
Yeah, I realized those other config calls too after body was working. Thanks!
Matrym
Nick - if I don't use parens in window.onload = lbp.init, how am I supposed to pas in config, which would override the default configurations?
Matrym
@Matrym - You can use an anonymous function, like this: `window.onload = function() { lbp.init({ optionsHere }); };`
Nick Craver