I am trying to dynamically make divs that are clickable. I have inserted a test function. The test function runs even though the div has not been clicked.
function displayResults(responseTxt)
{
var results = document.getElementById("results");
jsonObj = eval ("(" + responseTxt + ")");
var length = jsonObj.response.artists.length;
results.innerHTML = "Please click on an artist for more details: "
for ( var i = 0; i < length; i++)
{
var entry = document.createElement("div");
var field = document.createElement("fieldset");
entry.id = i;
entry.innerHTML = i + 1 + ". " + jsonObj.response.artists[i].name;
field.appendChild(entry);
results.appendChild(field);
//entry.addEventListener("click", idSearch(jsonObj.response.artists[i].id), false);
entry.addEventListener("click", test(), false);
}
} // end function displayResults
function test()
{
document.getElementById("results").innerHTML = "tested";
}
You are calling the
test()function and passing its return value to.addEventListener(). Remove the parentheses:So that you pass the function itself to
.addEventListener().That answers the question as asked, but to anticipate your next problem, for the line you’ve got commented out you’d do this:
That is, create an anonymous function to pass to
.addEventListener()where the anonymous function knows how to call youridSearch()function with parameters. Except that won’t work because when the event is actually triggerediwill have the value from the end of the loop. You need to add an extra function/closure so that the individual values ofiare accessible:That way the
iinjsonObj.response.artists[i].idis actually going to be the parameterifrom the anonymous function which is the individual value ofifrom the loop at the time each iteration ran.