Highlight new items added to list

In a component, I’m iterating over child components (notes) and listing relevant notes below the main card. I have added wire:poll.20s to the main component. Any new notes added by another user just appear in the list. All good, but I would like to draw the user’s attention to the fact that a new note was added.

Anyone any suggestions for this. I thought perhaps to use css (pref tailwind) to flash the background of the new element as it is added into the list, but don’t know how to achieve.

I think this needs to be done with JS. You need to either remove a class or add a class to do the transition on.

I have a solution… don’t know if its the best, but something for others to start with perhaps.

I added a recentlyUpdated accessor on the model

    public function getRecentlyUpdatedAttribute()
    {
        return $this->updated_at > now()->subseconds(60);
    }

So now I have a boolean to use in the view, true if the record was updated in the last 60 seconds. My cards refresh at 20 seconds so this is fine.

My note card looks like this

<div x-data x-init="removeClass($el,'bg-green-300',2500)" class="
    @if($note->recentlyUpdated) bg-green-300 @endif
    flex flex-row px-4 py-2 text-gray-700 transition-all duration-300 ease-in rounded shadow hover:bg-yellow-300" >
    <div class="flex-1 py-2">{!! nl2br(e($note->memo)) !!}</div>
    <div class="flex-none text-xs leading-snug text-gray-600">{{$note->user->name ?? 'anon' }}<br>{{ $note->updated_at->format('H:i D d/m/y') }}</div>
</div> 

Then in the parent component (or somewhere else in the page, I created this function;

    <script>
        function removeClass(el,theclass,delay){            
            setTimeout(() => {
                el.classList.remove(theclass);
            }, delay);
        }
    </script>

I made this general purpose by allowing the element, the class to be removed and the delay all attributes of the function.

So, when a new note appears, created by a different user, and detected by polling, it gets the bg-green-300 background added, then after 2.5 seconds the background is transitioned out. The removal of the class happens on all cards, but has no effect on cards that don’t have the background already.

1 Like