We help IT Professionals succeed at work.

dynamically adding onclick to div javascript help

flynny
flynny asked
on
Medium Priority
507 Views
Last Modified: 2012-05-06
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.
Comment
Watch Question

Top Expert 2007

Commented:
Where is "i" set?

Author

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
Top Expert 2007
Commented:
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.

Not the solution you were looking for? Getting a personalized solution is easy.

Ask the Experts

Author

Commented:
brilliant straight to the solution thanks for the help!
Top Expert 2007

Commented:
No worries - glad to help.
Access more of Experts Exchange with a free account
Thanks for using Experts Exchange.

Create a free account to continue.

Limited access with a free account allows you to:

  • View three pieces of content (articles, solutions, posts, and videos)
  • Ask the experts questions (counted toward content limit)
  • Customize your dashboard and profile

*This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.

OR

Please enter a first name

Please enter a last name

8+ characters (letters, numbers, and a symbol)

By clicking, you agree to the Terms of Use and Privacy Policy.