
Fixing missing tooltips for invalid required form controls
Fix missing tooltips for invalid form controls with scrollIntoView and IntersectionObserver.
When an HTML form control has the required
attribute and is not visible in the viewport, when the submit action is triggered, then the browser will scroll to the element when it’s invalid and the tooltip should be displayed as expected.

However, we’ve got a scenario when this was broken by other 3rd party code, and the tooltip was not displayed as expected. The form control got only focus. To resolve this issue we have used the combination of scrollIntoView
and IntersectionObserver API.
Solution implementation
const handleFormSubmit = (event) => {
const target = event.target;
const onSubmitValidationButton = target.closest('[data-action="onSubmitValidation"]');
if (onSubmitValidationButton === null) {
return;
}
const form = target.form;
const invalidElements = Array.from(form.querySelectorAll(':invalid'));
if (invalidElements.length > 0) {
const firstInvalidElement = invalidElements[0];
const intersectionObserverCallback = (entries) => {
if (entries[0].isIntersecting) {
observer.unobserve(firstInvalidElement);
form.reportValidity();
}
};
const observer = new IntersectionObserver(intersectionObserverCallback, { threshold: 1.0 });
observer.observe(firstInvalidElement);
firstInvalidElement.scrollIntoView({ block: 'center', behavior: 'smooth' });
event.preventDefault();
}
};
document.addEventListener('click', handleFormSubmit);
By combining scrollIntoView
and IntersectionObserver, 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.
That’s where the IntersectionObserver API comes in. By observing the intersection of the invalid form control with the viewport, we can detect when the control is fully visible and then call reportValidity()
to display the tooltip. This ensures that the tooltip is displayed only when the control is fully visible, providing a better user experience.
By combining scrollIntoView
and IntersectionObserver API, 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.
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.
Comments