473,395 Members | 1,996 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,395 software developers and data experts.

assigning event listener in bulk

Claus Mygind
571 512MB
I would like to assign the same eventListener to a variable number of links that I stream back to a page.

Here is the code:
Expand|Select|Wrap|Line Numbers
  1. for (var i = 0; i < cm.length; i++ )
  2. {
  3.  tr = tbody.insertRow(tbody.rows.length);
  4.  td = tr.insertCell(tr.cells.length);
  5.  td.innerHTML =    '<a href="" id="'+cm[i].BILLID+'" >'+cm[i].BILLID+'</a>'
  6.  
  7. }
  8.  
  9. g.sbGetNextId = document.getElementById('sbGetNextId');
  10. g.sbGetNextId.addEventListener("click", function(){g.findId(this);},false);
  11.  
  12.  
Is is possible in the code above to assign the same "name" to each of the links and then assign the listener to the tagName instead?

Or is this one of those places where you want that last parameter true/false to be set so the event bubbles up to each of the links?

Or do you assign the event listener to the document node that contains all the links?

Not really sure how this can be done without just coding it inline when streaming out the anchor.
Jul 1 '11 #1
10 2128
Dormilich
8,658 Expert Mod 8TB
in principle you would have to assign the event listener to each of the links. depending on the action of the event handler (and the underlying HTML structure) you may assign the event to a common parent.

whether you have the event in capturing or bubbling mode solely depends on the exact implementation requirement of the handler.

Is is possible in the code above to assign the same "name" to each of the links and then assign the listener to the tagName instead?
not sure what this is supposed to mean …
Jul 1 '11 #2
Claus Mygind
571 512MB
Ok here is some simple code to demonstrate my question. Please copy and paste, it should run fine just as is.

I want to try to use the coding technique you have suggested. I want to use "eventListeners" instead of "inline javascript code".

How can an eventListener be assigned to each of the links streamed out in the code below instead of the "onclick" event handler?

Expand|Select|Wrap|Line Numbers
  1. <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
  2. <html>
  3.  <head>
  4.     <script type="text/javascript">
  5.      <!--
  6.     var oData = ["Abe","Tom","Harry","John"];
  7.     function eventAction(obj){ alert(obj.id);}
  8.     function loadTable()
  9.     {
  10.             var tr, td;
  11.             var tbody = document.getElementById("tData");
  12.             for (var i = 0; i < oData.length; i++ )
  13.             {
  14.                 tr = tbody.insertRow(tbody.rows.length);
  15.                 td = tr.insertCell(tr.cells.length);
  16.                 td.innerHTML =    '<a href="" id="'+oData[i]+'" onclick="eventAction(this); return false;" >'+oData[i]+'</a>'
  17.             }
  18.     }
  19.     //-->
  20.     </script> 
  21.  </head>
  22.  
  23. <body onload="loadTable();">
  24.     <table>
  25.         <tbody id="tData">
  26.         </tbody>
  27.         </table>
  28. </body>
  29. </html>
  30.  
  31.  
Please keep in mind it is not a question about why I am streaming out the page this way, it is how to do it when the page is streamed out this way.

Also please note, I am only interested in a FireFox solution. This code will never run on IE or any other browser.

Please post a workable soulution which can be copied and pasted.

Thanks as always for your great suggestions.
Jul 5 '11 #3
Dormilich
8,658 Expert Mod 8TB
after line 15 or 16 (omitting the onclick attribute)
Expand|Select|Wrap|Line Numbers
  1. td.addEventListener("click", eventAction, false);
this requires some changes in the eventAction function:
Expand|Select|Wrap|Line Numbers
  1. // the event object is automatically passed as the one and only parameter
  2. function eventAction(evt)
  3.     // the current element is automatically assigned to this
  4.     alert(this.id);
  5.     // instead of "return false"
  6.     evt.preventDefault();
  7. }
and of course you should also omit the href attribute whose styling you can set via CSS. the handler function then simplifies to
Expand|Select|Wrap|Line Numbers
  1. // the event object is automatically passed as the one and only parameter
  2. function eventAction()
  3.     // the current element is automatically assigned to this
  4.     alert(this.id);
  5. }
Jul 5 '11 #4
Claus Mygind
571 512MB
I have tested out your suggestions and I have a couple of questions.

1. the assignment method you suggest, assigns the event to the table cell <td>, which in this case does not have an id. While I could assign the id to the cell in this case, it is not really what I want. In other applications I may want to insert multiple controls into one cell. So when run (see attached file) the alert of course is blank.

2. can you explain why you would want to change the styling on the "href"? And if so what styling would you give it where it still would appear as a link?

I still have not really wrapped my head around the prototype idea that you have previously suggested, but perhaps that is one of the ways to deal with this issue here, where once the links have been streamed out where they are associated with a function the prototype of the function can be changed to add the click eventListener. But I don't know how to put all that together.

Please download and modify the attached file. The re-upload with your suggestions. You are definitely giving me some great ideas here and I really appreciate it.


Here is the content of the attached sample file
Expand|Select|Wrap|Line Numbers
  1.  <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
  2.  <html>
  3.   <head>
  4.      <script type="text/javascript">
  5.       <!--
  6.      var oData = ["Abe","Tom","Harry","John"];
  7.  
  8. //     function eventAction(obj){ 
  9. //     alert(obj.id);
  10. //     }
  11.  
  12.     // the event object is automatically passed as the one and only parameter
  13.     function eventAction()
  14.     { 
  15.         // the current element is automatically assigned to this
  16.         alert(this.id);
  17.         // instead of "return false"
  18. //        evt.preventDefault();
  19.     }
  20.  
  21.     function loadTable()
  22.     {
  23.         var tr, td;
  24.         var tbody = document.getElementById("tData");
  25.         for (var i = 0; i < oData.length; i++ )
  26.         {
  27.             tr = tbody.insertRow(tbody.rows.length);
  28.             td = tr.insertCell(tr.cells.length);
  29.             td.addEventListener("click", eventAction, false);
  30.             td.innerHTML =    '<a href="" id="'+oData[i]+'" >'+oData[i]+'</a>'
  31.         }
  32.     }
  33.      //-->
  34.      </script> 
  35.   </head>
  36.  
  37.  <body onload="loadTable();">
  38.      <table>
  39.          <tbody id="tData">
  40.          </tbody>
  41.          </table>
  42.  </body>
  43.  </html>
  44.  
Attached Files
File Type: zip addEventListener.zip (729 Bytes, 83 views)
Jul 8 '11 #5
Dormilich
8,658 Expert Mod 8TB
1. you’re correct, I totally overlooked that. you’d have to do that on the <a> element
Expand|Select|Wrap|Line Numbers
  1. td = tr.insertCell(tr.cells.length);
  2. a  = td.appendChild(document.createElement("a"));
  3. // quick ’n’ dirty
  4. a.id = a.textContent = oData[i];
  5. a.addEventListener("click", eventAction, false);
2. I’d omit the href alltogether, because there is no need for it. therefore I don’t need to stop the default action of a hyperlink (<a> with href attribute)
e.g.
Expand|Select|Wrap|Line Numbers
  1. td a {
  2.     cursor: pointer;
  3. }


I still have not really wrapped my head around the prototype idea that you have previously suggested, but perhaps that is one of the ways to deal with this issue here, where once the links have been streamed out where they are associated with a function the prototype of the function can be changed to add the click eventListener.
what prototype? prototype is for the inheritance of objects, ’s got nothing to do with event handling.
Jul 8 '11 #6
Claus Mygind
571 512MB
Ok I got it to work with some modification.

In the code below, I changed the assignment to "a" instead of "td".

I added "var" in front of the creation of "a", otherwise "a" would have become a global variable.

Your suggestion about removing the "href", it appears you mean to say I eliminate the need to insert "preventDefault", but I would then have to insert something to turn the text blue and underline it by creating a css class and apply that class to the link.

The little quick and dirty assign a value to a variable from a variable that is being assigned, is nifty, I had never thought about that. "a.id = a.textContent = oData[i];"

Expand|Select|Wrap|Line Numbers
  1. var a  = td.appendChild(document.createElement("a"));
  2. // quick ’n’ dirty
  3. a.id = a.textContent = oData[i];
  4.  
  5. //td.innerHTML =    '<a href="" id="'+oData[i]+'" >'+oData[i]+'</a>'
  6.  
  7. a.addEventListener("click", eventAction, false);
  8.  
  9.  
  10.  
Finally I did not understand your code
Expand|Select|Wrap|Line Numbers
  1.    td a {
  2.        cursor: pointer;
  3.     }
  4.  
I could not see where it should fit in the context.
Jul 8 '11 #7
Claus Mygind
571 512MB
Also I am now curious, if I choose to assign "href" using the "appendChild" approach, it does not appear as an anchor link

Expand|Select|Wrap|Line Numbers
  1. var a  = td.appendChild(document.createElement("a"));
  2.  
  3. // quick ’n’ dirty
  4. a.id = a.textContent = oData[i];
  5. a.href=""
  6. a.addEventListener("click", eventAction, false);
  7.  
The property is added to the control but I do not get the link highlighting.
Jul 8 '11 #8
Dormilich
8,658 Expert Mod 8TB
Expand|Select|Wrap|Line Numbers
  1. var a  = td.appendChild(document.createElement("a"));
  2.  
  3. // quick ’n’ dirty
  4. a.id = a.textContent = oData[i];
  5. a.href=""
  6. a.addEventListener("click", eventAction, false);
  7.  
I don’t know how often I have to repeat it … if you don’t have a hyperlink (an <a> pointing to an URI) don’t use the href attribute!

wouldn’t it make more sense to add the variable declaration of a to where the others are? (var tr, td, a;)

The property is added to the control but I do not get the link highlighting.
then add it yourself via CSS. depending on what you understand by "link highlighting" the properties color and text-decoration as well as the pseudo-class :hover are of interest.
Jul 8 '11 #9
Claus Mygind
571 512MB
Yeah, I get it as I stated in the entry above. I just saw a lot of extra code being inserted. But I get it, it's a coding style separate html from formating and javaScript. I'm getting there.

I want it to be a link, but not in the traditional sense because I want to use it with an ajax call.
Jul 8 '11 #10
Dormilich
8,658 Expert Mod 8TB
I want it to be a link, but not in the traditional sense because I want to use it with an ajax call.
you may want to consider what to do with people without JavaScript (i.e. a fallback solution)
Jul 8 '11 #11

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

Similar topics

2
by: Neil Cherry | last post by:
I have to modifiy a program which uses a serial interface and event listeners. The modification entails adding support for connecting to a terminal server via an IP address and port number instead...
3
by: Csaba Gabor | last post by:
Is there a way to remove an anonymous event handler that I attached using attachEventListener? Or to say it another way, is there a way to remove all event handlers that have been attached to an...
6
by: Steve Teeples | last post by:
I have been perplexed by how to best treat an event that spans different classes. For example, I have a form which a user inputs data. I want to broadcast that data via an event to another...
6
by: Jeremy | last post by:
I want each instance of an object to be able to listen for input events. When the event occurs, a method of the object should be called, such that "this" is in scope and refers to the object...
6
by: Daz | last post by:
Hi, I am trying to find an event listener which will trigger when the pages starts loading, as opposed to when it's finished, or when the DOM content has finished loading. I am sure that such a...
6
by: Daz | last post by:
Hello everyone, I would like to open a child window from the parent, and add an onload event listener to the child window which will tell the parent when the document has loaded. As far as I...
0
daJunkCollector
by: daJunkCollector | last post by:
I wrote the following script. I have a movieclip named countyA_mc. I want the user to mouse over this movie clip, and result in the sending of a variable to the middle tier. I can establish...
1
Cristian Pinheiro
by: Cristian Pinheiro | last post by:
Hello guys, I was playing with Image Thumbnail Viewer (ITV) and found one problem, see http://www.dynamicdrive.com/dynamicindex4/thumbnail.htm for more details and how it works. Now the...
3
bugboy
by: bugboy | last post by:
i'm trying to avoid inline event handlers by creating a listener. What i'm trying is based on reading this: http://www.quirksmode.org/js/events_advanced.html I can't figure out what i'm doing...
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?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
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,...
0
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...
0
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...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...

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.