how to scroll to an element?

  • Last Update :
  • Techknowledgy :

2000 is the no of pixels I wanted to scroll towards the right. Use scrollTop instead of scrollLeft if you want to scroll your div down. To scroll to a given element, just made this javascript only solution below. Note that window.scroll({ ...options }) is not supported on IE, Edge and Safari. In that case it's most likely best to use element.scrollIntoView(). (Supported on IE 6). You can most likely (read: untested) pass in options without any side effects.

This is our Splunktool team suggestion ✌, we tried and its working fine
document.getElementById("divId").scrollIntoView();

scrollIntoView works well:

document.getElementById("divFirst").scrollIntoView();

You can use an anchor to "focus" the div. I.e:

<div id="myDiv"></div>

Suggestion : 2

The Element interface's scrollIntoView() method scrolls the element's ancestor containers such that the element on which scrollIntoView() is called is visible to the user. If false, the bottom of the element will be aligned to the bottom of the visible area of the scrollable ancestor. Corresponds to scrollIntoViewOptions: {block: "end", inline: "nearest"}. If true, the top of the element will be aligned to the top of the visible area of the scrollable ancestor. Corresponds to scrollIntoViewOptions: {block: "start", inline: "nearest"}. This is the default value.

1._
scrollIntoView()
scrollIntoView(alignToTop)
scrollIntoView(scrollIntoViewOptions)
2._
const element = document.getElementById("box");

element.scrollIntoView();
element.scrollIntoView(false);
element.scrollIntoView({
   block: "end"
});
element.scrollIntoView({
   behavior: "smooth",
   block: "end",
   inline: "nearest"
});

Suggestion : 3

The scroll method: The scroll() is used to scroll to the specified element in the browser.   The scrollTo method: The scrollTo() is used to scroll to the specified element in the browser.  The scrollIntoView method: The scrollIntoView() is used to scroll to the specified element in the browser.  Syntax:  Here, x-cord specifies the x-coordinate and y-cord specifies the y-coordinate. 

Syntax: 

element.scrollIntoView()
2._
<!DOCTYPE html>
<html>
    <head>
        <style>
            #condiv {
                height: 500px;
                width: 500px;
                overflow: auto;
                background: #82c93a;
            }
            #ele {
                top: 70%;
                height: 200px;
                width: 200px;
                background-color: green;
                position: absolute;
            }
        </style>
    </head>
    <body>
          
<p>Click the button to scroll to the element.</p>
  
        <button onclick="scrolldiv()">Scroll</button>
        <div id="condiv">
            <div id="ele">
                Pretagcode
            </div>
        </div>
        <script>
            function scrolldiv() {
                var elem = document.getElementById("ele");
                elem.scrollIntoView();
            }
        </script>
    </body>
</html>

Syntax:  Here, x-cord specifies the x-coordinate and y-cord specifies the y-coordinate. 

element.scroll(x - cord, y - cord)
6._
<!DOCTYPE html>
<html>
    <head>
        <style>
            #condiv {
                height: 500px;
                width: 500px;
                overflow: auto;
                background: #82c93a;
            }
            #ele {
                top: 70%;
                height: 200px;
                width: 200px;
                background-color: green;
                position: absolute;
            }
        </style>
    </head>
    <body>
          
<p>Click the button to scroll to the element.</p>
  
        <button onclick="scrolldiv()">Scroll</button>
        <div id="condiv">
            <div id="ele">
                Pretagcode
            </div>
        </div>
        <script>
            function scrolldiv() {
                window.scrollTo(0, 
          findPosition(document.getElementById("ele")));
            }
            function findPosition(obj) {
                var currenttop = 0;
                if (obj.offsetParent) {
                    do {
                        currenttop += obj.offsetTop;
                    } while ((obj = obj.offsetParent));
                    return [currenttop];
                }
            }
        </script>
    </body>
</html>

Suggestion : 4

Sometimes we need the user to click on a button or link and take them to an element present on the same HTML page. Also, this needs to take the user to the element without any reload. Lots of times, users tend to skip to the main content, like on a gaming Website. They might want to skip the instructions and want to play the game directly. So, basically, we want to scroll to a particular element or skip to content. Although we are skipping content, the behavior is still not smooth. You can observe that when we click on the links, we go directly to the desired section. But we can make it scroll smoothly to the desired section as well. Output: As you can see in the output, we are smoothly scrolling to the sections and skipping the contents as well.

1._
<!DOCTYPE html>
<html lang="en">
 
<head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width,
    initial-scale=1.0" />
    <title>Scroll</title>
    <style>
        section:target {
            border: 2px solid blue;
        }
 
        .links-container {
            display: flex;
            justify-content: space-between;
        }
    </style>
</head>
 
<body>
    <div class="links-container">
 
        <!-- The href attribute of anchor
            tags point to the section IDs -->
        <!-- Note that href has to point to IDs
            and not to classes as IDs are
            unique in HTML-->
        <a href="#id1">Go to Section 1</a>
        <a href="#id2">Go to Section 2</a>
        <a href="#id3">Go to Section 3</a>
        <a href="#id4">Go to Section 4</a>
    </div>
 
    <!-- We need to specify unique IDs for
        each section/div/element we want
        the user to scroll to -->
 
    <section id="id1">
        <h1>Section 1</h1>
    </section>
    <section id="id2">
        <h1>Section 2</h1>
    </section>
    <section id="id3">
        <h1>Section 3</h1>
    </section>
    <section id="id4">
        <h1>Section 4</h1>
    </section>
</body>
 
</html>
2._
<!DOCTYPE html>
<html lang="en">
 
<head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content=
        "width=device-width, initial-scale=1.0" />
 
    <style>
 
        /* Some basic styling for
        testing our functionality */
        .links-container {
            display: flex;
            justify-content: space-between;
        }
 
        .sections {
            display: flex;
            flex-direction: column;
            place-items: center;
            gap: 100rem;
        }
    </style>
</head>
 
<body>
    <div class="links-container">
 
        <!-- The href attribute of anchor
            tags point to the section IDs -->
        <a href="#id1">Go to Section 1</a>
        <a href="#id2">Go to Section 2</a>
        <a href="#id3">Go to Section 3</a>
        <a href="#id4">Go to Section 4</a>
    </div>
 
    <!-- We need to specify IDs for each
        section/div/element we want the
        user to scroll to -->
    <div class="sections">
        <section id="id1">
            <h1>Section 1</h1>
        </section>
        <section id="id2">
            <h1>Section 2</h1>
        </section>
        <section id="id3">
            <h1>Section 3</h1>
        </section>
        <section id="id4">
            <h1>Section 4</h1>
        </section>
    </div>
</body>
 
</html>

To do this, we can use the following line in our code:

scroll - behavior: smooth;

Suggestion : 5

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. The scrollIntoView method also accepts a parameter through which you can set an animated scroll behavior and also customize its alignment. behavior : This sets whether scrolling should be an animated one or an instant scroll to the element. It can have the following values :

1._
// element which needs to be scrolled to
var element = document.querySelector("#post-container");

// scroll to element
element.scrollIntoView();

This parameter scrollIntoViewOptions is an object with the following properties :

var element = document.querySelector("#post-container");

// smooth scroll to element and align it at the bottom
element.scrollIntoView({
   behavior: 'smooth',
   block: 'end'
});

Suggestion : 6

The scrollIntoView() method scrolls an element into the visible area of the browser window. Refs in React have many different applications. One of the most common uses is to reference elements in the DOM. By referencing the element, you also gain access element’s interface. This is essential to capture the element to which we want to scroll. Scroll to an Element With the Element.scrollIntoView() Method in React:

Syntex:

element.scrollIntoView(align)

By default set value is nearest.

Example:

var element = document.getElementById("box");
element.scrollIntoView();
element.scrollIntoView(false);
element.scrollIntoView({
   block: "end"
});
element.scrollIntoView({
   behavior: "smooth",
   block: "end",
   inline: "nearest"
});

useRef returns a mutable ref object whose .current property is initialized to the passed argument (initialValue). useRef() is useful for more than the ref attribute.

const divRef = useRef(null);
5._
class TestComponent extends Component {
  constructor(props) {
    super(props);
    this.testRef = React.createRef();
  }
  scrollToElement = () => this.testRef.current.scrollIntoView();
  
  render() {
    return <div ref={this.testRef}>Element you want in view</div>;
  }
}

In this part react provide inbuilt function scrollTo.

Syntex:

scrollTo(x, y)

Suggestion : 7

The scroll event is sent to an element when the user scrolls to a different place in the element. It applies to window objects, but also to scrollable frames and elements with the overflow CSS property set to scroll (or auto when the element's explicit height or width is less than the height or width of its contents). A scroll event is sent whenever the element's scroll position changes, regardless of the cause. A mouse click or drag on the scroll bar, dragging inside the element, pressing the arrow keys, or using the mouse's scroll wheel could cause this event. The style definition is present to make the target element small enough to be scrollable:

1._
<div id="target" style="overflow: scroll; width: 200px; height: 100px;"> Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</div>
<div id="other"> Trigger the handler</div>
<div id="log"></div>
2._
$( "#target" ).scroll(function() {  $( "#log" ).append( "<div>Handler for .scroll() called.</div>" );});
3._
$("#other").click(function() {
   $("#target").scroll();
});