Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is this function firing multiple times?

I'm filling this list:

<ul id="FolderList"></ul>

with a list of folders using jquery that produces 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 on a level 1 li item, the function myFunc() executes as expected. If i click on a "level 2" item (ie: FolderList2a), myFunc is being called twice. If i click on a 3rd level (ie: FolderList2bi) it gets called 3 times - and so on. Anyone know what's going on here?! Thanks in advance!

like image 788
Losbear Avatar asked Jul 04 '12 19:07

Losbear


Video Answer


2 Answers

The click events are bubbling up the Dom
If you want to prevent bubbling let myFunc return false

To stop the bubbling you'll need to access the event object, event.stopPropagation or event.cancelBubble depending on browser.

http://jsfiddle.net/Jetyc/3/

like image 59
Musa Avatar answered Oct 05 '22 23:10

Musa


You should pass a string as an argument, so quote it:

                                             .--.-----------------
                                             v  v
<li id="FolderList2a" onclick="return myFunc('2a')">Sub Item 1</li>

And also place return false in the end of your function:

function myFunc(id) {
    //do something

    return false;
};
like image 25
VisioN Avatar answered Oct 06 '22 00:10

VisioN