Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get consistent ScrollIntoView behavior

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);
    }
},
like image 910
suntruth Avatar asked Mar 07 '16 21:03

suntruth


People also ask

When should I use scrollIntoView?

The scrollIntoView () method is used for scrolling the elements on the viewport.

How do I use scrollIntoView?

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.

How do I scroll a page to an element?

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.


1 Answers

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.

like image 193
Kevin LeStarge Avatar answered Nov 02 '22 23:11

Kevin LeStarge