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