Search code examples
javascriptjqueryevent-bubbling

how to write an onclick function in order to prevent bubbling


Evening guys, I have an issue where a have a <td> tag and a <p> tag inside of it, both have onclick events, this is a textbook situation of the <p> onclick running the <td> onclick rather than its own. from what i have researched on here and elsewhere i have come to the understanding that this is caused by bubbling. However aparently knowing is only half the battle because i can not seem to find a way to implement a fix for this issue. Here is how i am currently attempting to work around it

html:

<table>
    <tr>
        <td>
            <p>text</p>
        </td>
    </tr>
</table>

jquery:

$(function(){
var show = function(){
    $('#editentry').css({'display': 'block'}); //this is column 3
}
//run var show on click
$('td p').click(function(event){
    show;
    event.stopPropagation();//stop bubbling
});
});//end function

i have also tried this:

$(function(){
var show = function(event){
    $('#editentry').css({'display': 'block'}); //this is column 3
    event.stopPropagation();
}
//run var show on click
     $('td p').click(show);
});//end function

from what i understand this should be working, sorry if i missed something simple, im a bit new to jquery and this seems to be a complicated subject. thanks in advance :)


Solution

  • What you have should work fine. That's exactly how you use stopPropagation.

    Here is an example to show how it stops the event from bubbling:

    HTML:

    <table>
      <tr>
        <td>
            <p>inside paragraph</p> outside paragraph
        </td>
      </tr>
    </table>
    

    Javascript:

    $(function(){
    
      $('td').click(function(event){
        alert('cell');
      });
      $('td p').click(function(event){
        event.stopPropagation();
        alert('paragraph');
      });
    });
    

    Demo: http://jsfiddle.net/39n5X/

    If you click on "inside paragraph" it will only show the "paragraph" message, and if you click on "outside paragraph" it will show the "cell" message instead.