Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jquery nested li click event calls multiple times

I have the following structure.

<ul id="browser" class="filetree">

        <li><span class="folder">Folder 1</span>

            <ul>

                <li><span class="file">Item 1.1</span></li>

            </ul>

        </li>

        <li><span class="folder">Folder 2</span>

            <ul>

                <li><span class="folder">Subfolder 2.1</span>

                    <ul id="folder21">

                        <li><span class="file">File 2.1.1</span></li>

                        <li><span class="file">File 2.1.2</span></li>

                    </ul>

                </li>

                <li><span class="file">File 2.2</span></li>

            </ul>

        </li>

        <li class="closed"><span class="folder">Folder 3 (closed at start)</span>

            <ul>

                <li><span class="file">File 3.1</span></li>

            </ul>

        </li>

        <li><span class="file">File 4</span></li>

    </ul>

In js I have the following function.

$("#browser li").click(function(){


});

When I clicked on li File 2.1.1. The function calls 3 times

first time for li File 2.1.1 , second time for li Subfolder 2.1 and third time for li Folder 2.

Can anyone give me the solution to call the function exactly once?

Your Help is greatly Appriciated. Thanks.

like image 689
Hardik Patel Avatar asked Jun 20 '12 16:06

Hardik Patel


3 Answers

That is because you have many li elements under #broswer.

Try this instead:

$("#browser>li").click(function(){
    //only direct children of #browser
    //your code
});

Or you can use event.stopPropagation():

$("#browser li").click(function(event){
    event.stopPropagation();
    //your code
});
like image 118
Naftali Avatar answered Sep 24 '22 17:09

Naftali


Change your function to

$("#browser li").click(function(event){
   event.stopPropagation();
   //do your other stuff

});

That way, the click on the lower-level li won't "bubble up" to the higher level li.

like image 45
Jacob Mattison Avatar answered Sep 26 '22 17:09

Jacob Mattison


This is due to the fact events "bubble" up your dom so you if you click

File 2.1.1, it will also be heard by File 2.1 and File 2 to fix this change event to

$("#browser li").click(function(e){
  //Your code here
  e.stopPropagation();
});
like image 31
AbstractChaos Avatar answered Sep 23 '22 17:09

AbstractChaos