Adding event listeners through an array and FOR loop

You have had a small problem in the last couple of days. I am trying to arrange my code as much as possible, and now I have a scene in which I am trying to add event listeners via JavaScript, so my HTML looks more neat.

-HTML segment

<input type="button" id="googleSearchButton" /> <input type="button" id="youtubeSearchButton" /> <input type="button" id="wikiSearchButton" /> <input type="button" id="facebookSearchButton" /> <input type="button" id="twitterSearchButton" /> <input type="button" id="tumblrSearchButton" /> <input type="button" id="dropboxSearchButton" /> 

JavaScript segment

 var contIDArray = ["google", "youtube", "wiki", "facebook", "twitter", "tumblr", "dropbox"]; window.load = initAll(); function initAll(){ applyProperties(); } function applyProperties(){ for (var i = 0; i < contIDArray.length; i++){ addEventListeners(contIDArray[i] + "SearchButton"); } } function addEventListeners(id){ document.getElementById(id).addEventListener("click", testAlert(id), false); } function testAlert(id){ alert(id + " clicked") } 

Theory

As I hope you can see, the FOR loop will loop until the value ends in the Array container. Each time, it displays a place in the array, and then "SearchButton". For example, the first time it launches, it displays "googleSearchButton", the second time "youtubeSearchButton" and so on.

Now I know that the FOR loop works to apply properties, because I use it to apply Button values ​​and text field in other segments of my project.

I added that it adds a simple test function ("testAlert ()") and sets the identifier of the called element for it. I installed it, so when event listeners were added, I can simply click on each button and it will alert its identifier and tell me that it was clicked.

Problem

Now, theoretically, I thought it would work. But it seems that the FOR loops trigger the addEventListeners function, which in turn adds an event listener to the testAlert when it is clicked. But it just runs the testAlert function as soon as it adds an event listener and doesn't fire when clicked.

I apologize if this seems a little big, but I always overdo my explanation. I hope you can see what I'm trying to do from my code, not explain.

Help would be much appreciated. :)

+4
source share
4 answers

You are there, but there is something wrong.

Firstly, you cannot just do id.addEventListener . You need to do document.getElementById(id).addEventListener . id is just a string, you need a DOMElement.

Secondly, when you execute testAlert(id) , you run the function and then assign its return value ( undefined ) as an event listener. You need to pass a function. For instance:

 id.addEventListener("click", function(){ testAlert(this.id); // this is the DOMElement you clicked on }, false); 

Although I suggest adding a class to all of your buttons, and then adding such an event.

 <input type="button" id="googleSearchButton" class="searchButton" /> <input type="button" id="youtubeSearchButton" class="searchButton" /> <input type="button" id="wikiSearchButton" class="searchButton" /> <input type="button" id="facebookSearchButton" class="searchButton" /> <input type="button" id="twitterSearchButton" class="searchButton" /> <input type="button" id="tumblrSearchButton" class="searchButton" /> <input type="button" id="dropboxSearchButton" class="searchButton" /> 

And then:

 var buttons = document.getElementsByClassName('searchButton'); for(b in buttons){ if(buttons.hasOwnProperty(b)){ buttons[b].addEventListener("click", function(){ testAlert(this.id); // this is the DOMElement you clicked on }, false); } } 

NOTE. addEventListener and getElementsByClassName may not be available in all browsers (I mean that they may not work in IE). This is why many websites use a JavaScript library such as jQuery . jQuery handles all cross-browser content for you. If you want to use jQuery, you can do this:

 $('.searchButton').click(function(){ testAlert(this.id); }); 

NOTE 2: In JavaScript, functions are variables and can be passed as parameters.

 document.getElementById(id).addEventListener('click', testAlert, false); 

Note that after testAlert there is no () , we pass this function, when you execute testAlert() , you pass its return value. If you do this like this, testAlert will need to be slightly modified:

 function testAlert(){ alert(this.id + " clicked") } 
+6
source

Edit:

 function addEventListeners(id){ id.addEventListener("click", testAlert(id), false); } 

for

 function addEventListeners(id){ document.getElementById(id).addEventListener("click", testAlert(id), false); } 

Otherwise, you apply addEventListener to the string. In any case, replace addEventListener with an event assignment, such as onClick .

+2
source

id looks like a string to me. So instead, do the following:

 function addEventListeners(id){ var obj = document.getElementById(id); obj.addEventListener("click", testAlert(id), false); } 

In addition, here is the working code:

http://jsfiddle.net/ZRZY9/2/

 obj.addEventListener("click", function() { testAlert(id); }, true); 

As Rocket mentions above, "you call it and set the event to the undefined return value."

Bad news: addEventListener () is currently not supported in Internet Explorer 7.

+1
source

I ran your code. The initial problem I ran into was that you were trying to find elements in the document before they were created. window.onLoad fires until the page is completed. I tested this using the onload attribute of the body tag, and it works that way.

So, this is a combination of the above problem with trying to find the element using the string "id" and a function that runs until the page loads completely.

In any case, I'm glad that you work it!

This is the javascript I had at the end:

  <script> var contIDArray = ["google", "youtube", "wiki", "facebook", "twitter", "tumblr", "dropbox"]; function initAll(){ applyProperties(); } function applyProperties(){ for (var i = 0; i < contIDArray.length; i++){ var newString = contIDArray[i] + "SearchButton" addEventListeners(newString); } } function addEventListeners(id){ document.getElementById(id).addEventListener("click", testAlert, false); } function testAlert(){ alert(this.id + " clicked") } </script> 
0
source

Source: https://habr.com/ru/post/1388320/


All Articles