+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 }) }

5/12/2019 2:49:48 AM

Ali

11 Answers

New Answer

+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).

+9

https://code.sololearn.com/W06DXnhIrqJz/?ref=app

+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

+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 !

+4

For a web developer like myself, the knowledge of the answers to this question is very important to me I guess

+4

This is because everytime the loop will call addEventListener, '_var[i]' will be 'undefined' as variable 'i' will already be 4. '_var[4]' will be 'undefined' here as there are only 4 divs but 'var[4]' is 5th, which doesn't exists. Use 'let' or this code: for(var i =0; i < _var.length; i++) { (function(i) { _var[i].addEventListener("click", function() { if(_var[i]) _var[i].style.backgroundColor = "blue"; }); })(i); } Read this posts to understand why var was causing error here. https://www.sololearn.com/discuss/1787117/?ref=app https://www.sololearn.com/Discuss/1777661/?ref=app

+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 🌷...

+3

Would be better if your post your code.....

+2

https://code.sololearn.com/WcrK9q8wYrAa/?ref=app round about line 100

+1

https://www.sololearn.com/post/91896/?ref=app

0

The problem is now solved Here is a demonstration on how it works https://code.sololearn.com/WfiGShUfT29w/?ref=app