I created a table using datatables and added a “More” button which triggers a mini-dropdown. This button and its dropdown content show perfectly, however, when I tried to distinctively show that the button is active anytime it is clicked using jQuery’s addClass()
or toggleClass()
functions, the button refuses to add or toggle the “active” class.
jQuery
JavaScript
x
4
1
$( "#dropdownDatatableButton" ).click(function() {
2
$( "#dropdownDatatableButton" ).addClass( "active" );
3
});
4
CSS
JavaScript
1
5
1
#datatablesDropdown .active {
2
background: rgb(37, 56, 88) !important;
3
color: rgb(255, 255, 255);
4
}
5
datatables
JavaScript
1
19
19
1
{ data: null,
2
render: function ( data, type, row, meta ) {
3
return '<div class="dropdown" id="datatablesDropdown">'
4
5
+ '<span class="material-icons btn datatables-more-btn" type="button" id="dropdownDatatableButton"' <!--here is the button that triggers the dropdown-->
6
7
+ 'data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">more_horiz</span>'
8
+ '<div class="dropdown-menu dropdown-menu-right datatables-dropdown-inner"'
9
+ ' aria-labelledby="dropdownDatatableButton">'
10
+ '<ul>'
11
+ '<li><a href="' + data.url.toLowerCase() + '/settings' + '">Board settings</a></li>'
12
+ '<li><a class="btn btn-link btn-sm text-left">Delete</a></li>'
13
+ '</ul>'
14
+ '</div>'
15
+ '</div>';
16
},
17
},
18
],
19
Advertisement
Answer
IDs must be unique in a page and you will also need to delegate the event listener since the plugin does re-renders for page changes, search, sort etc.
In addition you want to target the specific button the event occurred on
Try:
JavaScript
1
4
1
$('table').on('click', ".dropdownDatatableButton" ,function() {
2
$(this).toggleClass( "active" );
3
});
4
And change the ID to class in the html and css.