alpine-collective / alpine-magic-helpers

A collection of magic properties and helper functions for use with Alpine.js
https://npmjs.com/alpine-magic-helpers
MIT License
747 stars 19 forks source link

Scroll not working when loaded from another livewire component #148

Closed dcbndev closed 2 years ago

dcbndev commented 3 years ago

Hello, I am new to livewire/alpine and trying to debug an error in the console.

I have a livewire component, that renders a form step by step. When a radio input option is selected, the next radio input is loaded and available for selection. On click, the next radio input group is loaded and it scrolls to it. It works well until I load another livewire component inside current livewire component.

Inside first livewire component, I apply the scroll code x-data x-on:click="$nextTick(() => { $scroll('#calendarScroll', {behavior: 'smooth'}) })" It looks for the id="calendarScroll" inside second livewire component. Here I have another list of radio inputs, and after selecting one, the script turns back to the first livewire component to render remaining data.

When I click on a radio input from the second component, I get following error scroll.js:526 Uncaught TypeError: Cannot convert undefined or null to object at Function.assign (<anonymous>) at Proxy.<anonymous> (scroll.js:526) at eval (eval at tryCatch.el.el (app.js:182), <anonymous>:3:39) at app.js:1658 If I click twice on the same radio input, it scrolls to given id, that is inside first livewire component, as intended.

What may be the problem? Why it throws the error on first click?

SimoTod commented 3 years ago

@dcbndev Can you post a minimal script to replicate the issue? From the description above is not clear what you have on the click handler on your radio button but my gut feeling is that you are trying to scroll to an element that is not available on your page when you click the first time (maybe livewire loads it on click so it's available on the second click?)

dcbndev commented 3 years ago

@SimoTod you are right, I am trying to scroll to an element that is loaded when the radio input is clicked, so it doesnt exist at that time, that's why I get the null. Ive been told that a setTimeout of 500ms could help me with scroll. Can you give a hint on how to add 'setTimeout' to 'x-data x-on:click="$nextTick(() => { $scroll('#orderScroll', {behavior: 'smooth'}) })"'? Thank you

SimoTod commented 3 years ago

I would not use a timeout because that value is based on your network latency that you don't know that value upfront. The best way is to dispatch a browser event from livewire, listen for it in alpine an trigger the scrolling. See https://laravel-livewire.com/docs/2.x/events#browser