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...

Community
  • 1
  • 1
  • 1
    Did you mean `x.click(changecolor(x))`? – elclanrs Nov 30 '16 at 03: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. – nnnnnn Nov 30 '16 at 04:06

2 Answers2

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
Community
  • 1
  • 1
Pranav C Balan
  • 113,687
  • 23
  • 165
  • 188
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/

synz
  • 563
  • 3
  • 8