1

Possible Duplicate:
Doesn’t JavaScript support closures with local variables?

I want to add a different onclick dynamically to my div elements with 1 loop. This is a simplified version of my code.

var colors=['blue','green','yellow'];
var newtxt=['box1','box2','box3'];

var i;
function set_element2()
{
var x=document.getElementById('mydiv').getElementsByTagName('div');
  for(i=0;i<x.length;i++)
  {

    var d=x[i];
var col=colors[i];
    var txt=newtxt[i];
d.style.background=col;
d.onclick=function(){d.innerHTML=txt};

  }
}

i want each div when clicked to display newtxt[i]. What is stumping me is the colors change for my divs individually like they should, however the onclick is only affecting the last div. If i click div 0 or div 1 it only changes the inner html of div2 not each one individually.

function wrongway()
{
x[0].onclick=function(){x[0].innerHTML=newtxt[0];};
x[1].onclick=function(){x[1].innerHTML=newtxt[1];};
x[2].onclick=function(){x[2].innerHTML=newtxt[2];};
}

doing it this way works, however I need to do this in a loop so I dont have to create dozens of functions for each set of divs, and this is not DRY.

here is my html with the style of #mydiv div- height:50px; width:200px; border:1px solid black;

 <body>
 <section id='mydiv'>

    <div>
</div>

<div>
</div>

<div>
</div>


 </section>
 <input type='button' onclick='set_element2()'> 
 </body>

thanks for any answers, sorry if my wording is a bit confusing. tl;dr i want to add separate onclicks to a set of divs with 1 loop

editied for more clarity*

solution by specifying d.i=i, and using this the problem is solved.

function multOnclicks()
{
var x=document.getElementById('mydiv').getElementsByTagName('div');
for(i=0;i<x.length;i++)
{

  var d=x[i];
  var col=colors[i];
  var txt=newtxt[i];

  d.style.background=col;

  d.i = i;
  d.onclick=function(){this.innerHTML=newtxt[this.i]};

  }
}
4
  • Are you ok to use JQuery? Commented Jan 5, 2013 at 20:57
  • 1
    derive the colour on click Commented Jan 5, 2013 at 21:00
  • …or of infamous loop problem Commented Jan 5, 2013 at 21:03
  • sorry those links do indeed relate to this problem, maybe this will still help some people due to its simplicity. Commented Jan 5, 2013 at 21:16

1 Answer 1

0

Try this

d.onclick=function(){this.innerHTML=this.style.backgroundColor};

http://jsfiddle.net/UAvmx/

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

1 Comment

this did work but I edited my code to further clarify the problem. This answer finds the colors directly I need the innerHTML to display specific text.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.