Losbear
Losbear

Reputation: 3315

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!

Upvotes: 5

Views: 12881

Answers (5)

Musa
Musa

Reputation: 97672

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/

Upvotes: 10

Jerome WAGNER
Jerome WAGNER

Reputation: 22422

Basically what you are encountering 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 goes up in the hierarchy.

see an example on MDN Event propagation

Upvotes: 0

thorn0
thorn0

Reputation: 10397

The event fires multiple times because it bubbles. You can read more about the event bubbling, for example, here: http://www.quirksmode.org/js/events_order.html

Upvotes: 0

Etienne Dupuis
Etienne Dupuis

Reputation: 13786

You should use .bind() instead to avoid bubbling up the DOM.

$("#FolderList li").bind("click", function() {
//do stuff
});

Upvotes: 0

VisioN
VisioN

Reputation: 145398

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;
};

Upvotes: 1

Related Questions