I have a table cell which is clickable and fires a jQuery event when clicked. Within that cell I also have a button, which has another jQuery event when clicked. The issue is, when the button is clicked both the cell and button events are fired.
For example:
<script>
    $(document).ready(function () {
        $('#cell').click(function () {
            alert('cell clicked');
        });        
        $('#button').click(function () {
            alert('button clicked');
        });
    });
</script>
<table>
    <tr>
        <td id="cell">
            <button id="button">go</button>
        </td>
    </tr>
</table>
How can I prevent the cell click event being fired when the button is clicked?
You can use stopPropagation() which allow you to stop bubbling of event to the parent dom.
Example
$('#button').click(function (e) {
    e.stopPropagation();
    alert('button clicked');
});
set the table width to 100% and test it.
Test Code
<script type="text/javascript" src="js/jquery.js"></script>
<script type="text/javascript">
    $(function()
    {
        $('#cell').click(function () {
            alert('cell clicked');
        });        
        $('#button').click(function (e) {
            e.stopPropagation();
            alert('button clicked');
        });
    });
</script>
<table width="100%">
    <tr>
        <td id="cell">
            <button id="button">go</button>
        </td>
    </tr>
</table>
                        stop the event propagation which is called event bubbling to the parent:
$('#button').click(function (e) {
        e.stopPropagation();
        alert('button clicked');
    });
                        $(document).ready(function(){
   $('#cell').click(function(event){
     if($(event.target).is('#button')){
         event.stopPropagation();
      }    
   });    
});
                        You need to use
stopPropagation
This example should fix it:
$(document).ready(function () {
    $('#cell').click(function () {
        alert('cell clicked');
    });        
    $('#button').click(function (e) {
        e.stopPropagation();
        alert('button clicked');
    });
});
That should fix it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With