Event Listener inside a For Loop | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 6

Event Listener inside a For Loop

I am working on a web app and I need to handle many event listeners on an array of divs at the same time. Is there any way to do that inside a for loop because in my code the event listener is not working properly. The following is a sample of my code : //arr is an array of div elements for(var i = 0;i<10;i++){ arr[i].addEventListener(“click”,function(){ //code }) }

12th May 2019, 2:49 AM
Ali
9 Answers
+ 11
The logic is fine. I remember doing something similar in JS. We'll have to look at what arr stores and if al the objects are relevant when you attach the event listeners. It would be good if you can link your full code, or the error message which comes with it (if any).
12th May 2019, 2:59 AM
Hatsy Rei
Hatsy Rei - avatar
+ 7
I would suggest to add the event to one parent element of the divs than to all the divs. This approach will significantly increase the performance. Here is the example without the for loop and only using single event listner: https://code.sololearn.com/Ww7TS0vDx0Z5/?ref=app
12th May 2019, 9:11 AM
R R
+ 5
It might be good, if you included your code! Let me know if you wanna do the 'Same Work' with all of those Event Listeners! Like Biraj 's code shows !
12th May 2019, 5:44 AM
Arb Rahim Badsa
Arb Rahim Badsa - avatar
+ 4
For a web developer like myself, the knowledge of the answers to this question is very important to me I guess
12th May 2019, 2:45 PM
eMBee
eMBee - avatar
+ 3
Hatsy Rei No error occured during the execution of my program. It is just that the click event listeners did not work. My code is similar to Biraj’s code but i noticed that in his code he used for(let i =0... instead of for(var i=0... so i changed it and now the problem is solved but I don’t know why 😂 Thank you for your great responses 🌷...
12th May 2019, 6:29 AM
Ali
+ 3
Would be better if your post your code.....
12th May 2019, 2:59 PM
KrOW
KrOW - avatar
12th May 2019, 6:35 PM
Oma Falk
Oma Falk - avatar
12th May 2019, 12:02 PM
Gordon
Gordon - avatar
0
The problem is now solved Here is a demonstration on how it works https://code.sololearn.com/WfiGShUfT29w/?ref=app
12th May 2019, 8:37 PM
Ali