I have a livewire component and in the component blade file there is custom JS, and I have given a button for just a refresh of the component.
The problem is, when I click on the refresh button it does not execute custom scripts, but this custom script only works on the first page or first component load,
As soon as I click on Refresh, it does not work and comes to the default state.
How can I achieve scripts to execute when the component is loaded?
I tried with @script, document.addEventListener('livewire:initialized', () => { but did not worked.
<div>
<button type="button" class="btn btn-sm btn-light" wire:click="$refresh">Refresh</button>
</div>
<script>
function scrollToRow(className) {
var rowsToScroll = document.getElementsByClassName(className);
var tableContainer = document.querySelector('.table-container');
if (rowsToScroll.length > 0 && tableContainer) {
for (var i = 0; i < rowsToScroll.length; i++) {
var element = rowsToScroll[i];
var elementRect = element.getBoundingClientRect();
var containerRect = tableContainer.getBoundingClientRect();
var scrollableTop = elementRect.top - containerRect.top + tableContainer.scrollTop;
var middle = scrollableTop - (containerRect.height / 2) + (elementRect.height / 2);
tableContainer.scrollTo({
top: middle,
behavior: 'smooth' // Optionally, to scroll smoothly
});
}
}
}
...
//Some many JS ...
</script>
You need to add livewire listeners. Add to your JS code
And then, in your livewire component you need to add to refresh function