Reputation: 819
This questions sounds already been answered.
Been looking for answers and I keep getting back to event.stopPropagation()
answer. But why does it doesn't work on this fiddle? Am I missing something?
$(document).ready(function(){
$('#test-table').DataTable()
$('#test-table thead tr th').each(function(i, e) {
$(this).append('<button id="test-button" style="margin-left: 5px; margin-right: 5px;">Test Button</button>')
})
$('body').on('click', '#test-button', function(e) {
alert('test')
e.stopPropagation()
})
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" rel="stylesheet"/>
<link href="https://cdn.datatables.net/1.10.20/css/jquery.dataTables.min.css" rel="stylesheet"/>
<script src="https://cdn.datatables.net/1.10.20/js/jquery.dataTables.min.js"></script>
<table id="test-table" class="table table-striped table-bordered">
<thead>
<th>Name</th>
<th>Description</th>
</thead>
<tbody>
<tr>
<td>a</td>
<td>a</td>
</tr>
<tr>
<td>b</td>
<td>b</td>
</tr>
</tbody>
</table>
Upvotes: 1
Views: 778
Reputation: 765
Look at the JSFiddle: https://jsfiddle.net/0fyxws79/2/
You just need to change the selectors before applying on click event. a) Earlier button was getting selected with respect to body element & on body did not have any further event that's why you were not able to figure out whether stopPropagation is working or not.
b) Now button is found with respect to the table head which had sorting event attached to it. And whenever we clicked on button present inside table head it's stopping it's respective selectors events.
01) Fiddle: Here click event is attached to HTML body just for letting you know & your code from question is working here but in different manner. https://jsfiddle.net/0fyxws79/1/
02) Fiddle: Here sorting event was already present on table header & that was the one which we need to prevent on button click. That's working here https://jsfiddle.net/0fyxws79/2/
03) Fiddle: Where you can able to see difference between button elements which were present at the design time behaving with stopPropagation & button elements which were added dynamically behaving with stopPropagation.
https://jsfiddle.net/uk4ym30r/
$(document).ready( function () {
$('#example').DataTable();
$('#example thead tr th').each(function(i, e) {
$(this).append('<button id="test-button" style="margin-left: 5px; margin-right: 5px;">Test Button</button>');
});
$('th[class^="sorting"]').on('click', '#test-button', function(event) {
alert('test');
event.stopPropagation();
});
});
Upvotes: 2