Search code examples
javascripthtmldompolymershadow-dom

Smooth scrolling in the shadow DOM


I am working on a web app made with Web Components using Polymer. Each component has many child components each one with its own shadow DOM.

I am specifically working on a section with a big form with many fields, some of them outside the viewport. When I try to submit the form, a validation function is called. The validation function is tweaked so that it does not only return a boolean but sets an array with the invalid components called 'invalidElements'.

Then I can call focus on the first invalid element so that when I click submit the element focuses and comes into the viewport.

    invalidElements[0].focus()

The thing is that I would like to smoothly scroll to the invalid field. I can't use "scroll-behavior: smooth" because all ids are hidden under many shadow DOM's of parent components.

Even if I can get the id from invalidElement[0] ...

    invalidElement[0].id

... I can't access it after. I mean, I could, but it would imply to crawl the website entering every shadowDOM. Given the big size of the form, with it's many fields this would not be performant.

How could I then smooth scroll to the focused element?


Solution

  • If I understand you correctly, you like to scroll to element with out visiting any other controls.Then using Javascript you can achieve as below,

    invalidElement.scrollIntoView({ block: "center", inline: "center"});
    

    If you want to scroll to element slowly by visiting all the elements(smooth scroll), you can use below snippet.

    invalidElement.scrollIntoView({ block: "center", inline: "center", behavior: "smooth" });