AddEvenLister fires off immediately after being attached
- by Diego
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.