Lets say I have an element within a parent container. I want to scroll to that element, while keeping it vertically centered in the parent container. I wrote the following function that works on all browsers except for IE11:
// Function for scrolling to an element, and placing it in the middle of the view
// By default, the container parameter is set to the browser window
function scrollIntoViewMiddle(element, container) {
if (container === undefined) {
container = window;
}
var elementRect = element.getBoundingClientRect();
var absoluteElementTop = elementRect.top;
var middleDiff = (elementRect.height / 2);
var scrollTopOfElement = absoluteElementTop + middleDiff;
var scrollY = scrollTopOfElement - (window.innerHeight / 2);
container.scrollTo(0, scrollY);
}
Unfortunately, this does not work on IE11, as scrollTo()
is not a defined function or whatever. What is the alternative approach? Is there even a way to do this in IE11?
Since the scrollTo method doesn't support IE browser, we could set the Element.scrollLeft property and Element.scrollTop property to achieve the same effect.
Please refer to the following sample code:
<script>
function scrollWin() {
var con = document.getElementById("container");
var el = document.getElementById("goose");
scrollIntoViewMiddle(el, con);
}
function scrollIntoViewMiddle(element, container) {
if (container === undefined) {
container = window;
}
var elementRect = element.getBoundingClientRect();
var absoluteElementTop = elementRect.top;
var middleDiff = (elementRect.height / 2);
var scrollTopOfElement = absoluteElementTop + middleDiff;
var scrollY = (scrollTopOfElement - (container.getBoundingClientRect().height / 2));
//container.scrollTo(0, scrollY);
container.scrollLeft = 0;
container.scrollTop = scrollY;
}
</script>
Html resource and CSS style:
<style>
.scrollContainer {
overflow-y: auto;
max-height: 100px;
position: relative;
border: 1px solid red;
width: 120px;
}
.box {
margin: 5px;
background-color: yellow;
height: 25px;
display: flex;
align-items: center;
justify-content: center;
}
#goose {
background-color: lime;
}
</style>
<div id="container" class="scrollContainer">
<div class="box">duck</div>
<div class="box">duck</div>
<div class="box">duck</div>
<div class="box">duck</div>
<div class="box">duck</div>
<div class="box">duck</div>
<div class="box">duck</div>
<div class="box">duck</div>
<div id="goose" class="box">goose</div>
<div class="box">duck</div>
<div class="box">duck</div>
<div class="box">duck</div>
<div class="box">duck</div>
<div class="box">duck</div>
<div class="box">duck</div>
<div class="box">duck</div>
<div class="box">duck</div>
</div>
<button onclick="scrollWin()">Click me to scroll</button><br><br>
The result looks like this: