Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does my jQuery alert show twice?

Tags:

jquery

list

I am using jQuery. I have a problem when alerts the IDs of a list shows two times, instead of once.

The list:

<ul id="testnav">
    <li> <a href="#">Page 1</a></li>
    <li> <a href="#">Page2..</a>
        <ul id="subnav">
            <li id="content_1"><a href="#"> Page3</a></li>
        </ul>
    </li>
</ul>

The code:

$("li").click(function(){
    var current_id = $(this).attr('id');
    alert(current_id);
    // These alert two times, one is empty and another one is content_1
});

Why dopes the code alert two times? How do I make it execute a single time?

like image 866
venkatachalam Avatar asked Nov 27 '22 02:11

venkatachalam


2 Answers

$("li").click() is applying the click event to all LIs on the page.

When you click

<li> <a href="#">Page2..</a>
     <ul id="subnav">
          <li id="content_1"><a href="#"> Page3</a></li>
     </ul>
</li>

You're actually clicking the outer LI, and the inner-most LI, which would cause the event to fire twice. The outer LI has no ID, so it's empty, and the inner LI has an ID of "content_1", so that displays.

Does that make sense?

like image 147
Carl Avatar answered Dec 11 '22 03:12

Carl


Add event.stopImmediatePropagation(); to your event and then it won't fire twice:

$("li").click(function(event)
{
       event.stopImmediatePropagation();
});
like image 44
vikki_logs Avatar answered Dec 11 '22 04:12

vikki_logs