Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to scrollIntoView and scroll inner container without scrolling the whole body

Tags:

javascript

I have an outer container which includes inner container both with overflow. The inner container contains a few elements and I want to scrollIntoView for a specific element. What happens is that te body and inner containers scrolls, I want only the inner container to scroll.
Here is my code:

.outerContainer{
    height: 150vh;
    width: 100%;
    background-color: bisque;
}
.innerContainer{
    width: 500px;
    height: 80vh;
    background-color: aqua;
    overflow: auto;
}
li{
    height: 300px;
}
<div class="outerContainer">
    <div class="innerContainer">
        <ul>
            <li>1</li>
            <li>2</li>
            <li>3</li>
            <li id="target">4</li>
            <li>5</li>
        </ul>
    </div>
</div>
<script>
    document.getElementById("target").scrollIntoView();
</script>
like image 764
user2401856 Avatar asked Dec 06 '25 18:12

user2401856


1 Answers

You could save the current position of the window scroll, do the scrollIntoView() and then scroll back to the saved scroll position afterwards.

const { scrollX, scrollY } = window;
document.getElementById("target").scrollIntoView();
window.scroll(scrollX, scrollY);
.outerContainer{
    height: 150vh;
    width: 100%;
    background-color: bisque;
}
.innerContainer{
    width: 500px;
    height: 80vh;
    background-color: aqua;
    overflow: auto;
}
li{
    height: 300px;
}
<div class="outerContainer">
    <div class="innerContainer">
        <ul>
            <li>1</li>
            <li>2</li>
            <li>3</li>
            <li id="target">4</li>
            <li>5</li>
        </ul>
    </div>
</div>
like image 124
Wongjn Avatar answered Dec 08 '25 06:12

Wongjn



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!