Javascript – Object literal + document.body.onclick not doing what I expect

javascriptobject-literal

ok, people here is my amazing antigravity library. I'm trying to define it as an object literal, which, uh, i read all the cool kids are doing in order to to encapsulate their libraries. Basic tests indicate it's working properly, but I cannot seem to see document.body from inside my object.

what should happen is when I click on the page "It is working" should alert. Instead I get a document.body=null error. what gives? Where is my body? why can I not set a mouse event for it? I have wasted my whole friday day with this! Gah!

antigrav={
activate:function(){
    // turn on antigrav
    document.body.onmousedown = antigrav.startPan();
},

startPan:function(event){
    alert('it is working!');
},

}

document.onload=antigrav.activate();

Best Solution

You probably want to do

document.onload=antigrav.activate;

With parenthesis, you are setting document.onload to the result of running antigrav.activate(), instead of indicating you want antigrav.activate to run as the document.onload handler. Therefore, activate() was getting run in order to make the assignment, before the document was loaded, hence document.body wasn't defined yet.

You would want to do the same thing for the onmousedown handler assignment:

document.body.onmousedown = antigrav.startPan;

Trying this out, I also had to switch to window.onload...

Also, watch out for trailing commas in object literal definitions. Firefox is ok with them, but IE chokes. So, altogether:

var antigrav={
    activate:function(){
        // turn on antigrav
        document.body.onmousedown = antigrav.startPan;
    },
    startPan:function(event){
        alert('it is working!');
    }
};
window.onload=antigrav.activate;