On this page
Abstract backgorund and example HTML form on it

Fixing missing tooltips for invalid required form controls

Fix missing tooltips for invalid form controls with scrollIntoView and the scrollend event for reliable validation tooltip display.

When an HTML form control has the required attribute and is not visible in the viewport, when the submit action is triggered, the browser will scroll to the element when it’s invalid and the tooltip should be displayed as expected.

The HTML invalid form control with a tooltip "Please fill in this field."

However, we’ve encountered scenarios where this native behavior was broken — either by third-party code or due to browser inconsistencies. In some cases, the tooltip wasn’t displayed as expected, and the form control only received focus without showing the validation message.

Understanding the issue

The problem typically manifests in two ways:

  1. Third-party interference: external scripts or libraries may intercept or modify the default form validation behavior, preventing the native tooltip from appearing.
  2. Native browser behavior: when a form control is outside the current viewport, browsers may scroll to it but fail to display the native validation bubble. This can happen when the scrolling is triggered programmatically or when the browser’s default validation flow is interrupted.

To resolve this, we’ve developed a robust solution using a combination of scrollIntoView and the scrollend event, with a fallback for older browsers.

Solution implementation

Our improved approach eliminates the need for the IntersectionObserver API by leveraging the scrollend event, which provides more reliable detection of when scrolling has completed.

Scroll to the first invalid form control and display tooltip
private static setupFormValidation(): void {
    const forms = Array.from(document.querySelectorAll<HTMLFormElement>(FormUtility.onSubmitValidationSelector));

    if (forms.length === 0) {
      return;
    }

    const handleFormSubmit = (event: Event): void => {
      const target = event.target as Element;
      const submitButton = target.closest<HTMLButtonElement | HTMLInputElement>('button[type="submit"], input[type="submit"]');

      if (submitButton === null) {
        return;
      }

      const form: HTMLFormElement | null = submitButton.form ?? submitButton.closest('form');

      if (form === null || form.matches(FormUtility.onSubmitValidationSelector) === false) {
        return;
      }

      const firstInvalidElement: HTMLElement | null = form.querySelector<HTMLElement>(':invalid');

      if (firstInvalidElement === null) {
        return;
      }

      event.preventDefault();

      const rect: DOMRect = firstInvalidElement.getBoundingClientRect();
      const viewportHeight: number = globalThis.innerHeight;

      const isVisible: boolean = rect.top >= 0 && rect.bottom <= viewportHeight;

      if (isVisible) {
        form.reportValidity();
        return;
      }

      const reportValidity = (): void => {
        form.reportValidity();
      };

      if ('onscrollend' in globalThis) {
        const handleScrollEnd = (): void => {
          reportValidity();
        };

        globalThis.addEventListener('scrollend', handleScrollEnd, { once: true });

        firstInvalidElement.scrollIntoView({
          behavior: 'smooth',
          block: 'center'
        });

        return;
      }

      // Fallback for browsers without scrollend.
      firstInvalidElement.scrollIntoView({
        behavior: 'auto',
        block: 'center'
      });

      reportValidity();
    };

    document.addEventListener('click', handleFormSubmit);
  }

How the improved solution works

1. Visibility check

The solution first checks if the invalid form control is already visible in the viewport using getBoundingClientRect(). If it is, reportValidity() is called immediately to display the tooltip.

2. Scroll with detection

If the element is not visible, the code triggers scrollIntoView() to bring it into the viewport. For browsers that support the scrollend event (which includes modern versions of Chrome, Firefox, Safari, and Edge), we listen for this event to know exactly when scrolling has finished.

3. Fallback for older browsers

For browsers that don’t support scrollend, we fall back to immediate reportValidity() after an instant scroll (behavior: 'auto'). While this approach doesn’t account for scroll duration, it ensures the tooltip is displayed after the scroll completes.

Why this approach is better

  • Reliability: the scrollend event was specifically designed for detecting when scroll operations finish, making it more reliable than IntersectionObserver for this use case.
  • Simplicity: by removing the IntersectionObserver, the code is cleaner and easier to maintain.
  • Performance: fewer API calls and observers mean better performance, especially on pages with many forms.
  • Smoother UX: the smooth scrolling with behavior: 'smooth' provides a better user experience than instant scrolling.

By combining scrollIntoView and the scrollend event, we can ensure that the invalid form control is scrolled into view and the tooltip is displayed correctly, even when the control is not initially visible in the viewport.

Important considerations

  • Browser support: while scrollend is widely supported in modern browsers, having the fallback mechanism ensures your solution works across all environments.
  • Testing across devices: behavior can vary across different browsers and devices, particularly on mobile where scrolling and viewport interactions are different.
  • Third-party conflicts: if you’re experiencing issues, check whether other scripts are intercepting form submission events or modifying form validation behavior.

It’s worth noting that the behavior of scrolling to an invalid form element and displaying a tooltip can vary across different browsers and devices. You may need to test this solution across different environments to ensure it works as expected.

Workable example

Note: The CodePen example above demonstrates the original IntersectionObserver approach. We recommend implementing the updated scrollend approach for better reliability and performance.

Need help with digital accessibility?

Schedule a 30-minute session now!

Related posts

Comments

Leave a Reply

Search in sitelint.com

Is your site slow?

Discover performance bottlenecks to provide a better customer experience and meet your company’s revenue targets.