This is how Livewire works, it re-renders parts of your page and any custom js needs to be applied every time your component is rendered. One way to do it would be that you pass the state back and forth, and another would be to use the hooks to apply your custom js.
the dynamic css disappears on element
I have LIST of cards on a page. each card has item related info. there is a progress bar on each card. I have a js which looks at an item property and set inline CSS for progress bar. this is WORKING fine. (the js works for ALL items on the page)
When a user interacts with a card (by clicking a button)
- all the items progress bar changes to 0
- if i inspect the element and go to progress bar div, click a button, i can see for a split second JS adding the CSS to progress bar, but for some reason it is disappearing.
when user clicks a button, i fire a livewire event, then on the frontend i have js that looks at all the orogress bars, recalcuates % and assign css. i do have multiple components
main page:
<section id="main-section" class="campaigns">
<x-custom.campaign-grid :$campaigns/>
</section>
grid:
<div class="campaigns-grid">
@foreach ($campaigns as $campaign)
<livewire:components.campaign-summary :$campaign :key="$campaign->id"/>
@endforeach
{{ $campaigns->links() }}
</div>
<script type="text/javascript">
function updateProgressBar() {
var progressBars = document.getElementsByClassName("js-progress-bar");
for (const progressBar of progressBars) {
var elem = document.getElementById(progressBar.getAttribute('id'));
var style = 'linear-gradient(90deg, #8B5CF6 ' + progressBar.dataset.value + '%, #14B8A6 0%)';
elem.style.background = style;
}
}
document.addEventListener('livewire:init', () => {
updateProgressBar();
// listening for the event
Livewire.on('userupdate', params => {
updateProgressBar();
});
});
</script>
finally campaign-summary component
<div>....
<div class="campaign-progress-bar">
<div id="{{ $campaign->id }}-progress-bar"
class="progress js-progress-bar"
data-value="{{ $campaign->percentage_raised }}"
></div>
</div>
...
</div>
initially i had the js in the base campaign card, and it was working fine but firing multiple times because component was being re-rendered.. so i moved it up a bit to grid component
Please or to participate in this conversation.