So I have been using ScrollIntoView() to jump to anchors in a react component as part of a web app. For small pages, it works fine, goes to the right spot and behaves as one would expect. I have one larger page where the behavior is strange. On loading, the jump to anchor is below where it should be by half a page or more. The first time one clicks on a link to any anchor, including the same anchor, the anchor ends up above where it should be by a similar amount. Every subsequent click after that works perfectly as long as the page is not reloaded. Here is my code for the function. It has a setTimeout because I thought that the problem had something to do with the page loading, but there is no effect. Here is my function:
scrollToAnchor: function () {
let anchorName = this.props.location.hash || window.location.hash;
if (anchorName) {
anchorName = anchorName.replace("#", "");
let anchorElement = document.getElementById(anchorName);
if (anchorElement) {
window.setTimeout(anchorElement.scrollIntoView(true), 0);
}
} else {
window.scrollTo(0, 0);
}
},
The scrollIntoView () method is used for scrolling the elements on the viewport.
JavaScript scrollIntoView() Example First, select the button with the btn class and list item with the special class. Then, attach an event listener to the click event of the button. Finally, scroll the JavaScript list item into the viewport by calling the el. scrollIntoView(true) method in the click event handler.
Scrolling to an element can be achieved in Javascript using the scrollIntoView() method. Smooth animation and customizing the alignment can be set through the scrollIntoViewOptions parameter.
In my case, I had to add the default params manually in order for it to work in some browsers. The block
and inline
params have an associated default value, but I had to put them in manually like this:
my_element.scrollIntoView(
{ behavior: 'smooth' , block: 'start', inline: 'nearest'}
);
Once I defined them in the scrollIntoViewOptions, it worked fine across all browsers.
PS: don't forget the polyfill for smooth scrolling.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With