March 18, 2013

How to control jQuery events when you have nested HTML?

Question by Cristian David Jimenez Duarte

For example:

<ul>
<li>
   first element
   <ul>
    <li> second element
       <ul>
          <li> third element </li>
       </ul>
      </li>
   </ul>
</li>
</ul>

<script>
$('li').click( function() {
   alert('hello world!!!');
});
</script>

The output is:

THREE ALERTS WHEN I CLICK THE THIRD ELEMENT

TWO ALERTS WHEN I CLICK THE SECOND ELEMENT

ONE ALERT WHEN I CLICK THE FIRST ELEMENT

How to prevent with jQuery this?

What I’m needing is: ONE ALERT FOR EACH CLICK IN ANY ‘LI’ ELEMENT.

Answer by Starx

As you have nested li elements. The click handler applies to all li elements including the parent li‘s.

You need to stop propagating the event bubble. So that once it execute the event handler, it does not goes up the DOM tree to trigger the same event.

$('li').click( function(e) {
   alert('hello world!!!');
   e.stopPropagation();
});

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+

...

Please fill the form - I will response as fast as I can!