dynamically adding onclick to div javascript help

hi all,

i've added an onclick method dynamically to a div

div.onclick = function() { alert(i); removeSection(i); };

where i is an integer in a for loop

now this seems to be working fine (if i break into this line it says i is incrementing as it should)

however when i click on the div the alert always reads 0.

any ideas why?

many thanks matt.
flynnyAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

 
BadotzCommented:
Where is "i" set?
0
 
flynnyAuthor Commented:
Hi i've managed to work out what was going on

it seems that because i pass i to the method that i.e.

for(i=0;i<array;i++)
{
addsection(i);
}

addSection(i)
{
div.onclick = function() { alert(i); removeSection(i); };
}

that is aissigning the pointer rather than the value to the onclick event? so if i then create a local variable it works?

do you know why this is the case?

matt
0
 
BadotzCommented:
Because this is wrong:

div.onclick = function() { alert(i); removeSection(i); };

It should be:

div.onclick = function(i) { alert(i); removeSection(i); };

You have to pass the variable all the way through.
0

Experts Exchange Solution brought to you by ConnectWise

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
 
flynnyAuthor Commented:
brilliant straight to the solution thanks for the help!
0
 
BadotzCommented:
No worries - glad to help.
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.