problem with addEventListener in firefox

  • Thread starter Generale Cluster
  • Start date
G

Generale Cluster

Hello,
I have an unordered list with sublists in it and I've used it to make an
expandable tree menu.
This is my sample page: http://tinyurl.com/y88ouj8
When I click on "prodotti", I get that "Clienti" submenu expands. I
would expect the "prodotti" menu to expand when clicking it.
My problem is that when I call addEventListener in firefox, it seems to
attach the listener always to the same element.
What is the problem in the code?
Thank you
Regards
 
M

Matthias Reuter

Generale said:
My problem is that when I call addEventListener in firefox, it seems to
attach the listener always to the same element.
What is the problem in the code?

That is the code:

function hideByClassName(clName) {
list = document.getElementsByTagName("ul");
for (i=0;i<list.length;i++) {

if (list.className==clName) {
var oText = document.createTextNode("+");
list.style.display="none";
var mynode=list;

list.parentNode.insertBefore(oText,list.parentNode.childNodes[0]);
try {
list.parentNode.childNodes[1].addEventListener("click",
function(evt){toggle(mynode,evt)}, true);
} catch (err) {
list.parentNode.attachEvent("onclick",
function(evt){toggle(mynode,evt)});
}
}
}
}

The problem lies here:

function(evt){toggle(mynode,evt)}

mynode is a reference. You expect it to point to the element it referenced
when you added the event listener, but is is evaluated when the handler is
called. Therefore mynode points to the last item of list.

A solution is to extract the target in toggle:

function toggle (e) {
var event = e || window.event;
var target = e.target || e.srcElement;

// ...
}


Matt
 
G

Generale Cluster

Matthias Reuter ha scritto:
Generale said:
My problem is that when I call addEventListener in firefox, it seems
to attach the listener always to the same element.
[CUT]
The problem lies here:

function(evt){toggle(mynode,evt)}

mynode is a reference. You expect it to point to the element it
referenced when you added the event listener, but is is evaluated when
the handler is called. Therefore mynode points to the last item of list. [CUT]
Matt

thank you
regards
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,995
Messages
2,570,230
Members
46,819
Latest member
masterdaster

Latest Threads

Top