I’m running into an issue with the addEventListener() function. I’m trying to build a menu based on variables from an array (I won’t bother explaining why it’s setup this way).
Here is the code:
var _Dirt = document.getElementById("dirt");
_Dirt.addEventListener('mouseover', function () { menuOver(true, this, _dirtY); }, false);
_Dirt.addEventListener('mouseout', function () { menuOver(false, this, _dirtY); }, true);
var _DirtDiv = _Dirt.getElementsByTagName('div')[0];
for (nLink in Men["dirt"]) {
var _lnk = document.createElement('p');
_lnk.className = 'menu';
_lnk.innerHTML = Men["dirt"][nLink][0];
_lnk.addEventListener('click', menuLoop(Men["dirt"][nLink][1]), false);
_DirtDiv.appendChild(_lnk);
_DirtDiv.innerHTML+= '<br />';
}
Here is the menuLoop function (in case you are concerned that I’m not correctly binding the variable right:
function menuLoop (n) {
return function () {
menuLink (n);
}
}
Now, the annoying part is that the event listener is working fine on the _Dirt element, but not at all on the _lnk element. Even when I change it to to _lnk.onclick = function () { //something }, it won’t work (as a matter of fact, the onclick attribute won’t even show up in the DOM).
I have another loop function that also attaches an event listener to an element, and that one works perfectly fine…and the code is very similar. What adds to the frustration is that this code used to work flawlessly. I actually don’t even recall making any changes to this code at all. I tried to isolate this function in the code to see if there were any breakpoints in my script, but it the issue remains.
Please let me know if you require any other parts of my code.
(This is under the assumption your data structures are all correct)
Your problem is
This basically takes the child nodes of
_DirtDiv, serializes them to a string (HTML), concatenates'<br />'and assigns it back toinnerHTML. The browser will parse the string and create the corresponding DOM nodes.The identity of the DOM node you created before is lost and so is the event handler. This process destroys and creates new DOM nodes which are different than the one you created before.
If you want to add a
brnode, use DOM manipulation as well:Example from the Chrome console which demonstrates that the nodes are different: