Reputation: 153
I had used offsetTop in my solution as follows.
public getOffsetTop = element => {
let offsetTop = 0;
while (element) {
offsetTop += element.offsetTop;
element = element.offsetParent;
}
return offsetTop;
};
const field = document.getElementById("error");
const totalOffsetTop = this.getOffsetTop(field);
window.scrollTo({
top: totalOffsetTop,
behavior: "smooth"
});
This works smoothly. Whenever there is an error, i am able to scroll back automatically to the error field. However, here is the real issue. offsetTop is experimental and should not be used in production. https://caniuse.com/#feat=mdn-api_htmlelement_offsettop
I tried using getBoundingClientRect().top but it doesnot scroll back to the error field. Can anyone suggest a better alternative ??
Upvotes: 2
Views: 1946
Reputation: 153
Just so it helps someone, i tried this and it worked.
public getOffsetTop = element => {
const rect = element.getBoundingClientRect();
const scrollTop =
window.pageYOffset || document.documentElement.scrollTop;
return rect.top + scrollTop;
};
Upvotes: 0
Reputation: 2930
What about Element.scrollIntoView()?
You could just:
document.getElementById("error").scrollIntoView({ behavior: 'smooth' });
Upvotes: 3