Reputation:
I am making a web app using javaScript and in one part, a list is dynamically generated. I want to make each list item to be clickable and a function to execute.
Anyhow, I note that the function is executed automatically when the page is loaded, even without clicking and when I click on it later, nothing happens.
Here is the code:
window.onload=function loadData(){
var goalsStr = localStorage.getItem("goalsNames");
var goalsObj = JSON.parse(goalsStr);
if (goalsObj !== null)
for(var i=0; i<goalsObj.length; i++){
var node = document.createElement("LI");
node.setAttribute("draggable", "true");
node.setAttribute("id","i");
var textnode = document.createTextNode(goalsObj[i]);
node.appendChild(textnode);
node.addEventListener('click', viewGoal(goalsObj[i]), false);
document.getElementById("sortable").appendChild(node);
}
}
function viewGoal(goal){
alert("this should not happen");
}
I even tried using .setAttribute('onclick', method, but that too is not working. What's wrong? What should I do?
Upvotes: 2
Views: 84
Reputation: 104775
When you're adding the event listener, you need to pass in a function, meaning, don't include the ()
-- else it will execute immediately!
node.addEventListener('click', function() {
viewGoal(goalsObj[i])
}, false);
Upvotes: 5