Pages

Tuesday, April 30, 2013

Jquery text repeat when used with on click and append

For example:

<script  type="text/javascript">
jQuery(
  function($)
  {
    $('div')
      .click(function(e)
             {
              $('span',this).append('A');
             }
            );
  }
);
</script>
<div><div><b>click here:</b><span></span></div></div>


If you click on the text, the click will trigger on the inner div and bubble up to the outer div, the function will be executed 2 times.
To avoid this use stopPropagation()

<script  type="text/javascript">
jQuery(
  function($)
  {
    $('div')
      .click(function(e)
             {
              e.stopPropagation();
              $('span',this).append('A');
             }
            );
  }
);
</script>
<div><div><b>click here:</b><span></span></div></div>