Cannot assign a function to JavaScript event; o_O.

Discussion in 'JavaScript' started by stewart:howe, Nov 21, 2007.

  1. #1
    Alright, well I am trying to assign a function to a JavaScript Event for a retrieved element.

    I will explain with code first :

    
    
    window.onload = function() {
    
        var divBox = document.getElementById(someid)
        var divBox.onclick = someOtherFunction(arg,arg)
    
    }
    
    function someOtherFunction(arga,argb){
        var anotherDiv = document.getElementById(someid)
            anotherDiv.style.color='blue'
    }
    
    
    Code (markup):
    If I attempt to do something similar to the above code, it executes 'someOtherFunction' rather than just setting the onclick event to the function with the proper arguments that I need to send it.

    Any suggestions ? Thanks a lot guys :)
     
    stewart:howe, Nov 21, 2007 IP
  2. joebert

    joebert Well-Known Member

    Messages:
    2,150
    Likes Received:
    88
    Best Answers:
    0
    Trophy Points:
    145
    #2
    You'll never use var before assigning a property of an object.

    These are right.
    var myvar = '';
    var myObj = {};
    myObj.prop = '';
    Code (markup):
    This is wrong.
    var myObj.prop = '';
    Code (markup):
    When you use the execution operators ( & ) after a function object, it executes. Doesn't matter if it's outright like the following.
    myFunc();
    Code (markup):
    Or during assignment like this.
    var myResult = myFunc();
    Code (markup):
    To pass arguments you need to wrap the call in an anonymous function, like this.
    divBox.onclick = function(){
       someOtherFunction(arg,arg);
    }
    Code (markup):
    Once you get used to using Legacy events, or maybe even before, you should look into addEventListener & attachEvent.
     
    joebert, Nov 21, 2007 IP