473,796 Members | 2,640 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

dynamic onclick problem

107 New Member
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 1750
gits
5,390 Recognized Expert Moderator Expert
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 New Member
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 Recognized Expert Moderator Expert
just put it where you assign your onclick event ... it just replaces that ...

kind regards
Mar 25 '08 #4
hkma08
11 New Member
[HTML]<html>
<head>
<script language="javas cript">
function initialise(){
data = {"item 1" : "a","item 2" : "b", "item 3" : "c"};
for (key in data)
{
itemDiv = document.create Element("DIV");
itemDiv.innerHT ML = key;
itemDiv.id = key;
itemDiv.onclick = function(){aler t(this.id);}
document.body.a ppendChild(item Div);
}
}
</script>
</head>

<body onload="initial ise();">
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 New Member
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 Recognized Expert Moderator Expert
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
7934
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 header of the datagrid in the "ItemDataBound" method of the grid. However, once, they are added in the grid, i seem to lose the event handler for the same control. Is there anyone who has tried this before and knows why this is hapenning ??
1
2501
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 post. In this post I want to ask you why my code behaves differently in IE, while it behaves like I expect in Mozilla and Opera. What I would like to see addressed is what I need to do to get the same behaviour in all 3 browsers. I know each browser...
4
2152
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 "TAG#") when more than 1 number (see "VLANS") is inputed into my form. QUESTION: How do I make my dynamic form have a dynamic input box(which is created by checking the checkbox and calling the functionC1) inside it and still be able to pass the...
3
1910
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 been looking around online for solutions, but the fixes I have seen don't seem to work. I assume I am misunderstanding something... I was using element.setAttribute but have changed my code to avoid that. Here is an example. IE6 displays the link...
1
1550
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 type='text'> object 02) by using appendChild () method, I've successfully append the button and the textbox under the div tag (or container in this case) 03) but now I would like to add the javascript onclick event on the button I've just created...
1
1976
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 is dynamic based on the index of the loop. In Firefox this is no problem. However in IE I get some results that I wouldn't expect. Here is my code:
3
5401
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 the html page. But if I try to navigate to another pdf in the IFRAME then no caching occurs. Is the problem in the IFRAME reloading instead of just refreshing the pdf? <SCRIPT type="text/javascript"> var pageNo; var nav; var iframe; var...
0
3398
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 within options. I have everything being dynamically named from the previously dynamically named element. (I hope this makes sense.) I am not able to retrieve any of the dynamically created values. I can view them on the source page but can't pull them...
3
4224
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 value (text value) here is the code if possible please help me Thanks beforehand <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
0
9673
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9524
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 effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10217
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10168
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
1
7546
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5440
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5568
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
3730
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2924
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.