473,385 Members | 1,764 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,385 software developers and data experts.

dynamic onclick problem

107 100+
Hi Guys,

Im trying to create lots of divs all with there own onclick event...

Heres the code:

Expand|Select|Wrap|Line Numbers
  1. <html>
  2. <head>
  3. <script language="javascript">
  4.  
  5. function initialise(){
  6.     data = {"item 1" : "a","item 2" : "b", "item 3" : "c"};
  7.  
  8.     for (key in data)
  9.     {
  10.         itemDiv = document.createElement("DIV");
  11.         itemDiv.innerHTML = key;
  12.         itemDiv.id = key;
  13.  
  14.         var otherDiv = itemDiv;
  15.         itemDiv.onclick = function(){alert(otherDiv.id);}
  16.         document.body.appendChild(itemDiv);
  17.     }
  18.  
  19. }
  20. </script>
  21.  
  22. </head>
  23. <body onload="initialise();">
  24. body text.
  25. </body>
  26. </html>

Seems like no matter what way i do it the onclick events all end up being the same as whichever one was created last.

I put the var otherDiv = itemDiv; line in to try and change this, but its still the same.

Can anyone help??


Cheers

Andy
Mar 20 '08 #1
6 1738
gits
5,390 Expert Mod 4TB
use the following 'explicit' closure construct:

Expand|Select|Wrap|Line Numbers
  1. itemDiv.onclick = function(param) {
  2.     return function() { alert(param); };
  3. }(otherDiv.id);
kind regards
Mar 20 '08 #2
theS70RM
107 100+
sorry i dont really understand how this works.

can you sub it into my posted code so the example works.

Thanks

Andy
Mar 25 '08 #3
gits
5,390 Expert Mod 4TB
just put it where you assign your onclick event ... it just replaces that ...

kind regards
Mar 25 '08 #4
hkma08
11
[HTML]<html>
<head>
<script language="javascript">
function initialise(){
data = {"item 1" : "a","item 2" : "b", "item 3" : "c"};
for (key in data)
{
itemDiv = document.createElement("DIV");
itemDiv.innerHTML = key;
itemDiv.id = key;
itemDiv.onclick = function(){alert(this.id);}
document.body.appendChild(itemDiv);
}
}
</script>
</head>

<body onload="initialise();">
body text.
</body></html>[/HTML]

Two logical reasons it doesn't work:
1. there is no use to state var otherDIv = itemDiv. This would just create another div element with empty content
2. most important is that, in each for loop steps, you used the same var (itemDiv), in first loop itemDiv = item 1, second loop itemDiv = item 2, last loop you set itemDiv = item 3. When all javascript finished, it use item 3 as variable and alert item3.id, that is why you always got item 3 as result. Instead, you can use this.id to refer to its own id when you click on an item.

Is this clear enough?
Mar 25 '08 #5
theS70RM
107 100+
Ah yes,

That does make it a bit clearer thanks.

I didnt understand that it was alerting the same variable for each one, i thought it would treat each one as a new instance.


Cheers


Andy
Mar 26 '08 #6
gits
5,390 Expert Mod 4TB
Two logical reasons it doesn't work:
1. there is no use to state var otherDIv = itemDiv. This would just create another div element with empty content
2. most important is that, in each for loop steps, you used the same var (itemDiv), in first loop itemDiv = item 1, second loop itemDiv = item 2, last loop you set itemDiv = item 3. When all javascript finished, it use item 3 as variable and alert item3.id, that is why you always got item 3 as result. Instead, you can use this.id to refer to its own id when you click on an item.

Is this clear enough?
in for-loops you have to use closures for such assignments ... that is exactly what i showed you with the given example. as you can see it passes a reference to the function that is immediatly executed and the returned function stores that passed reference and alerts the correct id ...

the 'this-construct' should work too ... but sometimes you just need the loop-index or something that is not in the this-context of the current node in your handler function and then you need the closure ...

kind regards
Mar 26 '08 #7

Sign in to post your reply or Sign up for a free account.

Similar topics

8
by: Ashish Shridharan | last post by:
Hi All I have been trying to add a control to the header cell of a datagrid on my ASP.NET page. These controls are defined in the HTML as ASP.NET web controls. They are being added into the...
1
by: Macamba | last post by:
Hi all, I am currently developing a website for a voluntary organisation. It is my first step in website development. The dynamic menu I developed has some bugs, which I addressed in another...
4
by: pizzy | last post by:
INTRO: I tried to clean it up for easy reading. I hope I didn't make any mistakes. PROBLEM: WOW, this is some crazy sh!t. I can't get my checkbox (see "TAGSELECTED") to print my textboxes (see...
3
by: Aaron Gervais | last post by:
I am brand-new to javascript, but after reading some tutorials online I was able to make a dynamic HTML photo gallery in javascript. It works fine in all browsers except IE6 (big surprise). I've...
1
by: kusanagihk | last post by:
To all, I'm working on a javascript to dynamic build a common set of HTML controls. 01) I've used the DOM object to build a <div> tag; then build 1 <input type='button'/> and 1 <input...
1
by: comicgeekspeak | last post by:
Hi there, I am trying to write a loop that will add 10 divs to the screen. Each div will have an onclick event. The function that will be called onclick requires a parameter. That parameter...
3
polymorphic
by: polymorphic | last post by:
I have succeeded in embedding PDF files in a dynamic iframe. The problem is that I need the PDF to cache. If the PDF remains the same from page load to page load then the pdf is somehow cached with...
0
bmallett
by: bmallett | last post by:
First off, i would like to thank everyone for any and all help with this. That being said, I am having a problem retrieving/posting my dynamic form data. I have a form that has multiple options...
3
by: azegurb | last post by:
hi I have just took from internet dinamic table. this table is dynamic and its rows dynamically can be increased. but i would like how create SUM function that automatically sums each added row...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.