Target filter with JS and change position
Target filter with JS and change position
I'm using MediaWiki (the Wikipedia software) with the database extension Cargo to display results in a DataTable. The extension creates the DataTable automatically without giving me the option to specify the table ID or add other configurations. It generates this code:
<div id="DataTables_Table_0_wrapper" class="dataTables_wrapper">
<div class="dataTables_length" id="DataTables_Table_0_length">...</div>
<div id="DataTables_Table_0_filter" class="dataTables_filter">
<label>Search: <input type="search" aria-controls="DataTables_Table_0"></label>
</div>
<table class="cargoDynamicTable display dataTable" id="DataTables_Table_0">...</table>
<div class="dataTables_info" id="DataTables_Table_0_info">...</div>
<div class="dataTables_paginate paging_simple_numbers" id="DataTables_Table_0_paginate">...</div>
</div>
I want to move the filter wrapper/input to a different position on the page (outside the DataTable wrapper) using JS/jQuery, but I cannot get it to work, probably because the DataTable/Filter hasn't loaded yet when the script runs. However, the script below does works when doing a hard refresh (not when doing a soft refresh again):
$(window).on('load', function () {
$(".dataTables_filter").prependTo("#my-element");
});
Styling the filter input with CSS works fine:
.dataTables_filter input { background:yellow; }
I've been reading through similar questions here (and in JS forums), and think initComplete might be what I'm looking for, but since I'm not initializing the DataTable, I'm not sure where or how to apply the setting to the existing table/filter.
Any help would be highly appreciated and I apologize in advance if I haven't included all necessary details in my question.
This question has an accepted answers - jump to answer
Answers
Yep, as you say, you'll be unable to latch onto the
initComplete
function as you have no control over that. However, you can use DataTables events instead, similar to theload
in your OP. I suspect usinginit
should do the trick,Colin
Yes, thank you very much! At first I was trying to apply init to "#DataTables_Table_0", but after changing the selector to "#myWrapper table", it worked.