I have a javascript code to make a slider, and inside the slider, there are content changes when calling a method via livewire, and the problem is when calling it, the slider blows up, and the javascript code won't work.
view:
@foreach($section->children()->get() as $subSection)
<button wire:click="serviceChanger({{ $subSection->id }})">{{ $subSection->name }}</button>
@endforeach
@foreach($services as $service)
the services here changes depending on the serviceChanger method
@endforeach
javascript
<script>
var swiper = new Swiper('.swiper-container', {
slidesPerView: 1,
spaceBetween: 10,
// init: false,
pagination: {
el: '.swiper-pagination',
clickable: true,
},
breakpoints: {
640: {
slidesPerView: 1,
spaceBetween: 20,
},
768: {
slidesPerView: 2,
spaceBetween: 40,
},
1024: {
slidesPerView: 4,
spaceBetween: 50,
},
}
})
</script>
component:
public function serviceChanger($id)
{
// some logic
}
after I call the ServiceChanger, the javascript won't work when the services change. Any Ideas?
I solve my problem by Dispatching a Browser Event at the end of the serviceChanger
method
$this->dispatchBrowserEvent('contentChanged');
in the JavaScript, file Catch the event like that
window.addEventListener('contentChanged', event => {
// your JS code
});
You need to re-initialize your javaScript code when Livewire refreshes the content.
When livewire replaces the HTML in the DOM with your new HTML, none of the JS code executes
You have to manually make sure everything executes again
For More Info take a look at Livewire Event