Reputation: 591
I want to know how to correctly add an Event Listener like onClick to a dynamic div. Here’s my snippet:
var $menu = new Array(2);
createDiv('yes');
function createDiv(title) {
var $class = 'menuLink';
var $title = 'title';
for(var i=0; i<$menu.length;i++)
{
$title = 'title';
var newdiv = document.createElement('div');
newdiv.setAttribute('class', $class);
newdiv.setAttribute('id', 'item'+i);
newdiv.addEventListener('onclick', clickHandle(newdiv.id),false);
if (title)
{
newdiv.innerHTML = $title;
} else {
newdiv.innerHTML = "No Title";
}
document.getElementById('menu').appendChild(newdiv);
showMenu();
}
}
function clickHandle(e)
{
if(e == 'item0')
{
alert('Link is' + ' ' + e);
}else{
alert('Another Link');
}
}
Here's my problem, the snippet works fine, It creates my divs, adds id's values and all, but the event fires off as soon as the event is attached, so while the for loop is creating the divs the alert window says: Link is item0, and immediately after this it says: Another Link.
Am I misunderstanding this? (I used this method zillions of times in AS3 with the expected result, just attached a function waiting for a click). What I want is that my Divs wait for the user to click on them, not to fire off immediately after of being attached. Thanks for any hint on this one. Greetings.
Ps. IE doesn't support addEventListener, but I want to resolve this before cross to the IE sea of madness, but I will appreciate the IE approach as well. - I tried "onclick" and just 'click' into the addEventListener line, both with the same result described above.
Upvotes: 0
Views: 759
Reputation: 382404
Replace
newdiv.addEventListener('onclick', clickHandle(newdiv.id),false);
with
(function(newdiv){
newdiv.addEventListener('onclick', clickHandle(newdiv.id), false);
})(newdiv);
The event wasn't triggered but you were calling clickHandle(newdiv.id)
and passing the result of this call to addEventListener
. Note also that the name of the event is 'click'
, not 'onclick'
.
Additionally, the variable newdiv was changed by the following loop. That's why I suggest to enclose it in a closure to prevent its variations.
You may also use this :
(function(newdiv){
newdiv.onclick = function(){clickHandle(newdiv.id)};
})(newdiv);
Upvotes: 2
Reputation: 389
since you already use jquery why not use it on your event binding?
Its cross-browser-compatible so you don't have to worry about IE anymore
try .click();
Upvotes: 0