/** * @example * scrollWindowToFirstFormError(); * // Scrolls the window to the first element that has the `js-form-error` class or the `p-message-error` class * * @example * scrollWindowToFirstFormError(".some-class"); * // Scrolls the window to the first element that matches the specified selector * * By default, this function scrolls to 70 pixels above the element that it * finds. This amount can be adjusted by using a CSS custom property named * `--virgodev-bazaar-scroll-window-to-first-form-error-subtraction-amount`, for * example: * * :root { * --virgodev-bazaar-scroll-window-to-first-form-error-subtraction-amount: 100; * } */ export default function scrollWindowToFirstFormError( querySelector = ".js-form-error, .p-message-error" ): void { const firstError = document.querySelector(querySelector); if (firstError) { let subtractionAmount: string | number = window .getComputedStyle(firstError) .getPropertyValue( "--virgodev-bazaar-scroll-window-to-first-form-error-subtraction-amount" ); if (/^\d+$/.test(subtractionAmount)) { subtractionAmount = parseInt(subtractionAmount, 10); } else { subtractionAmount = 70; } const domRect = firstError.getBoundingClientRect(); window.scrollTo({ top: domRect.top + document.documentElement.scrollTop - subtractionAmount, left: domRect.left + document.documentElement.scrollLeft, behavior: "smooth", }); } }