Environment: Firefox 16/27 and Chrome 33
I have a <div>
(with scroll bar) containing lots of elements <p>
.
If I call scrollIntoView()
on a <p>
element, I expect only the scroll of the div
to move, but the complete page (outside of the <div>
) gets scrolled.
Example on JSFiddle: http://jsfiddle.net/7fH8K/7/
What is going wrong here?
Native method: scrollIntoView The usage is simple, just like this: function scroll(e) {e. scrollIntoView({behavior: "smooth", block: "start"});}scroll(document. getElementById(YOUR_DIV_ID));
scrollIntoView(true);", element); This works for vertical scrolling but not for horizontal.
The scrollIntoView() method scrolls an element into the visible area of the browser window.
Just call scrollIntoView()
with the parameter false
to indicate that it should not be scrolled to the top.
See the description for Element.scrollIntoView()
on MDN for more info.
The reason why the JSFiddle page is scrolled down is that scrollIntoView()
scrolls all scrollable ancestor elements to display the element you called scrollIntoView()
on. And because the <body>
of the page is actually higher than the viewport but only scrolling is hidden via overflow: hidden;
, it scrolls the page down trying to align the p
element with the top.
Here's a simple example of this behavior:
File scroll.html:
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
<title>Main page</title>
<style type="text/css">
html, body {
height: 120%;
width: 100%;
overflow: hidden;
}
header {
height: 100px;
width: 100%;
background-color: yellow;
}
iframe {
height: 100px;
width: 300px;
}
</style>
</head>
<body>
<header></header>
<iframe src="scroll2.html"></iframe>
</body>
</html>
File scroll2.html:
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
<title>Scrolling <iframe></title>
<script type="text/javascript">
function scrollLastParagraphIntoView() {
var lastParagraph = document.getElementById("p10");
lastParagraph.scrollIntoView();
}
</script>
</head>
<body>
<button onclick="scrollLastParagraphIntoView()">Scroll last paragraph into view</button>
<p>Paragraph 1</p>
<p>Paragraph 2</p>
<p>Paragraph 3</p>
<p>Paragraph 4</p>
<p>Paragraph 5</p>
<p>Paragraph 6</p>
<p>Paragraph 7</p>
<p>Paragraph 8</p>
<p>Paragraph 9</p>
<p id="p10">Paragraph 10</p>
</body>
</html>
When you click the Scroll last paragraph into view button, the whole page will be scrolled so that the paragraph is displayed at the top of the viewport.
You can use:
scrollIntoView({ block: 'end' })
or for smooth scroll:
scrollIntoView({ block: 'end', behavior: 'smooth' })
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