Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript scrollIntoView only in immediate parent

How do I make scrollIntoView only scroll the immediate parent (e.g. div with overflow-y: scroll;) and not the whole page?

I have a web interface I'm making for an internal, very-specific purpose. Among other elements on my page is a div with a specified height and overflow-y is scroll.

I have data which will periodically appear in this area and I want it to always be scrolled to the bottom (e.g. the console output of a subprocess on some remote server).

If I use scrollIntoView, it scrolls the overflow-y div..... but also scrolls the whole page.

On a computer with a large monitor, this isn't an issue, but on my laptop with a smaller screen it also scrolls the whole window, which is definitely not the intended/desired behavior.

like image 348
iAdjunct Avatar asked Jun 20 '19 14:06

iAdjunct


Video Answer


2 Answers

I think what you might be looking for is

.scrollIntoView({block: "nearest", inline: "nearest"});

Where supported (basically anywhere except IE and SafarIE) this will do the 'least' movement to show the element; so if the outer container is visible, but the target element is hidden inside that container -- then it should scroll the inner container but not the page.

like image 177
Iain Ballard Avatar answered Sep 21 '22 23:09

Iain Ballard


I think you're looking for a combination of scrollTop and scrollHeight. You can use the first to set where you want the div to scroll to, and the second to get the height of all the info in the div:

var scrollyDiv = document.getElementById("container");
scrollyDiv.scrollTop = scrollyDiv.scrollHeight

setInterval(() => {
  var textnode = document.createElement("P");
  textnode.innerHTML = "Whatever"
  scrollyDiv.appendChild(textnode);  
  scrollyDiv.scrollTop = scrollyDiv.scrollHeight
}, 1000)
#container {
  height: 200px;
  overflow-y: scroll;
}

#big-content {
  height: 400px;
  background-color: green;
}
<div id="container">
  <div id="big-content"></div>
  <p>The bottom</p>
</div>
like image 21
dbramwell Avatar answered Sep 25 '22 23:09

dbramwell