MauroBaptista.com

Scroll to first validation error

Laravel Alpine Livewire

I got this problem, and I solve it like this:

How make your Add at the end of the body tag.

1<script>
2 document.addEventListener('alpine:init', () => {
3 Alpine.directive('navigate', (el, { expression }) => {
4 let first = document.querySelector('[x-navigate]');
5
6 if (first !== el) {
7 return;
8 }
9
10 const elementPosition = first.getBoundingClientRect().top + window.scrollY;
11 const offsetPosition = elementPosition - (parseInt(expression) || 100);
12
13 window.scrollTo({
14 top: offsetPosition,
15 behavior: 'smooth'
16 });
17 });
18 })
19 </script>

Then you can use it in your error component:

1@props(['for', 'offset' => 100])
2
3@error($for)
4 <p x-navigate="{{ $offset }}" {{ $attributes->merge(['class' => 'text-sm text-red-600 dark:text-red-400 mt-1']) }}>{{ $message }}</p>
5@enderror

When an x-navigate shows in page, it will scroll for the first component.