Why does this function fire several times?
I fill this list:
<ul id="FolderList"></ul> with a list of folders using jquery, which generates the following HTML:
<ul id="FolderList"> <li id="FolderList0" onclick="return myFunc(0)">Item 1</li> <li id="FolderList1" onclick="return myFunc(1)">Item 2</li> <li id="FolderList2" onclick="return myFunc(2)">Item 3 <ul> <li id="FolderList2a" onclick="return myFunc(2a)">Sub Item 1</li> <li id="FolderList2b" onclick="return myFunc(2b)">Sub Item 2 <ul> <li id="FolderList2bi" onclick="return myFunc(2bi)">Subsub Item 1</li> </ul> </li> </ul> </li> </ul> ...
function myFunc(id) { //do something return false; };
For some reason, if I click element 1 of level 1, the myFunc () function executes as expected. If I click on the Level 2 item (that is: FolderList2a), myFunc is called twice. If I click on the 3rd level (i.e.: FolderList2bi), it will be called 3 times - and so on. Does anyone know what is going on here ?! Thanks in advance!
An event fires several times because it is bubbling. You can learn more about event bubbles, for example, here: http://www.quirksmode.org/js/events_order.html
Basically what you meet is called Event Bubbling.
When you click on a nested set of elements, the click is first sent to the deepest element in the hierarchy, and then it rises in the hierarchy.
see example on MDN Event Propagation