Reputation: 191
I can't add an event to a newly created element.
The following code is executed upon onload
.
It shows the alert "blah" on page refresh for the number of times new elements are created, but these elements are not clickable after loading.
Any ideas?
for (var S = 0; S < arrInbound[i][3].length; S++){
var namesDiv = document.createElement('div');
namesDiv.id = S;
namesDiv.draggable = 'true';
namesDiv.contenteditable = 'true';
namesDiv.className = "crewNames";
//namesDiv.ondragstart = 'dragStart(event)';
//namesDiv.onblur = 'updateArr(this)';
namesDiv.onclick = alert("blah");
namesDiv.innerHTML = arrInbound[i][3][S];
tagElRight.appendChild(namesDiv)
}
Upvotes: 0
Views: 50
Reputation: 33
Your onclick is not a function, because you set onclick to result of alert execution. Try next:
namesDiv.onclick = function() {alert("blah")};
Upvotes: 1
Reputation: 11930
This is function assignment
namesDiv.onclick = function() { alert('a'); } // CORRECT
This is function call, namesDiv.onclick
is result of alert fn, which is undefined
namesDiv.onclick = alert('a'); // WRONG
More simplified example
var myBar = alert('apple'); //calls alert instantly
var myFoo = function() {
alert('banana');
}
console.log('myBar', myBar); //logs undefined
console.log('myFoo', myFoo); //logs fn
Upvotes: 2