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>
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>
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