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
$( "#dropdownDatatableButton" ).click(function() { $( "#dropdownDatatableButton" ).addClass( "active" ); });
CSS
#datatablesDropdown .active { background: rgb(37, 56, 88) !important; color: rgb(255, 255, 255); }
datatables
{ data: null, render: function ( data, type, row, meta ) { return '<div class="dropdown" id="datatablesDropdown">' + '<span class="material-icons btn datatables-more-btn" type="button" id="dropdownDatatableButton"' <!--here is the button that triggers the dropdown--> + 'data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">more_horiz</span>' + '<div class="dropdown-menu dropdown-menu-right datatables-dropdown-inner"' + ' aria-labelledby="dropdownDatatableButton">' + '<ul>' + '<li><a href="' + data.url.toLowerCase() + '/settings' + '">Board settings</a></li>' + '<li><a class="btn btn-link btn-sm text-left">Delete</a></li>' + '</ul>' + '</div>' + '</div>'; }, }, ],
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:
$('table').on('click', ".dropdownDatatableButton" ,function() { $(this).toggleClass( "active" ); });
And change the ID to class in the html and css.