0

I created div elements by the loop and I want to change background-color when I click the div.

var c = $("#container")[0];
for(var i=0; i<6;i++){
  var x = document.createElement("div");
   x.className = "sqare";
   x.click(changecolor(this));
   c.appendChild(x);
}
function changecolor(p){
  return function() {
    p.css("background-color", "yellow");
 }
}

I follow this Assign click handlers in for loop , but failed...

2
  • 1
    Did you mean x.click(changecolor(x))? Commented Nov 30, 2016 at 3:58
  • The value of this will be the same for every iteration of the loop, and from the code shown it's not clear what value that is (window, if that code is in the global scope). Also, x is a DOM element, so its .click() method doesn't assign a click handler. Commented Nov 30, 2016 at 4:06

2 Answers 2

1

Where this does not refer to the element which may refer to the window object instead pass the x as argument and css() is a jQuery method so either you need to wrap it using jQuery or update style property using JavaScript. Although attach click event by setting onClick property.

var c = $("#container")[0];
for(var i=0; i<6;i++){
  var x = document.createElement("div");
   x.className = "sqare";
   x.onClick = changecolor(p);
   c.appendChild(x);
}
function changecolor(p){
  return function() {
    p.style.backgroundColor = "yellow";
 }
}

The closure can be avoided here since this context can be accessed within the handler.

var c = $("#container")[0];
for(var i=0; i<6;i++){
  var x = document.createElement("div");
   x.className = "sqare";
   x.addEvenetListener('click', changecolor);
   c.appendChild(x);
}
function changecolor(){
   this.style.backgroundColor = "yellow";
}


Refer : addEventListener vs onclick

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

4 Comments

x.click(changecolor(x)); won't work - a DOM element's .click() method doesn't assign a click handler...
@nnnnnn : yes you are right, need to use onClick or addEventListener instead
Yep. Although the whole closure-in-a-loop thing wouldn't be necessary at all if the click handler used this...
@nnnnnn : I think for that we need to use addEventListener or attachEvent
0

You don't have to add event handler for each elements.

You can try to use only 1 click event.

Check my example below

SIMPLE HTML

<div id="container"></div>

JAVASCRIPT

var c = $("#container");
for(var i=0; i<6;i++){
    $("<div class='sqare'>hello " + i + "</div>").appendTo(c);
}

$(".sqare").on("click",function(){
    $(this).css("background-color","yellow");
});

And live example : https://jsfiddle.net/synz/amnapc70/

Comments

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.