1

I have an existing JavaScript function:

function changeColor(ID){

    try{
        initialize();
    }
    finally{
        changeDesign(ID);
    }
    
}

I want to do something like this:

for(var x=0; x<2; x++){
        document.getElementById(x).onclick = "changeColor(" + x +")";
}

The output with the html should be:

<tr bgcolor="#FFFFFF" id="0" onclick="changeColor(0)>
5
  • ids should not begin with a digit. Commented Jul 4, 2013 at 9:16
  • @JonathanNaguin Its not working...If I click the tr...nothing is happening... Commented Jul 4, 2013 at 9:21
  • @FelixKling I also tried 'document.getElementById(x).onclick = changeColor(x);' but when I run the application, it performs the function...what I want is for the user to first click the tr before the function is performed. Commented Jul 4, 2013 at 9:23
  • Is that so surprising? changeColor(x) calls the function changeColor and then the return value will be assigned to .onclick. If I do var foo = bar(42);, then bar will be executed and the return value will be assigned to foo. That's how function calling works (but now worries, people seem to get confused when it's about event handlers ;)). Commented Jul 4, 2013 at 9:24
  • @pmark019: See the answer by Felix Kling. You must not include (0) because then you say: "Run the function and set the return value as onclick event". Commented Jul 4, 2013 at 9:26

1 Answer 1

5

Assigning an event handler via the DOM API does not modify the actual HTML (in fact, the HTML source that the browser receives is readonly).

You have to assign a function to .onclick, not a string:

for(var x=0; x<2; x++){
    document.getElementById(x).onclick = changeColor;
}

where changeColor is defined as

function changeColor(){
    var ID = this.id; // `this` refers to element the handler is bound to

    try{
        initialize();
    }
    finally{
        changeDesign(ID);
    }

}

I recommend to read the excellent articles about event handling on quirksmode.org.

Sign up to request clarification or add additional context in comments.

2 Comments

Alternatively you can provide input parameter by wrapping in inline function like this: document.getElementById(x).onclick = function(){changeColor(x)};. This is useful if you need input parameters that is not accessible as properties on the element, only at the time of event binding.
Right, in this case you would have to use an IIFE though, to capture the value of the variable x: (function(x) { document.getElementById(x).onclick = function(){changeColor(x)}; }(x));.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.