Home > database >  Scrolling text inside div container not visible
Scrolling text inside div container not visible

Time:10-01

I have a div with inside some phrase example:

<div class="container">
  <div class="phrase-doc">Lorem ipsum bla bla</div>
  <div class="phrase-doc">Lorem ipsum bla bla</div>
  <div class="phrase-doc">Lorem ipsum bla bla</div>
  <div class="phrase-doc active">Lorem ipsum bla bla</div>
  <div class="phrase-doc">Lorem ipsum bla bla</div>
  <div class="phrase-doc">Lorem ipsum bla bla</div>
  <div class="phrase-doc">Lorem ipsum bla bla</div>
</div>
<button class="btn">Move</button>

when i click on the button i want move the scroll on the active phrase, i use this code

this.el.nativeElement.querySelector('.phrase-doc.active').scrollIntoView();

and work good only if the container it's visible on the page, but if the container it's not visible, the page scroll move on it, i want the page scroll stay in the same position and only the scroll inside container move on the active phrase and the container should not scroll into view if it is not visible.

CodePudding user response:

and the container should not scroll into view if it is not visible.

This is problematic because there is no API that supports that. The aim of scrollIntoView is to make that content visible.

What you could do is to get the scroll position of each scrollable ascendants save their value and after the scrollIntoView call restore those.

The drawback of that is that you can use smooth scrolling for the scrollable ascendants (if that is a requirement) and scrollIntoView (or at least not without additional work).

document.querySelector('.btn').addEventListener('click', () => {

  // here you should check all ascendants of `container` that a scrollable
  // instead of doing that only for window
  const {
    scrollX,
    scrollY
  } = window
  
  document.querySelector('.phrase-doc.active').scrollIntoView({
    block: 'nearest',
    inline: 'start'
  });
  
  // here you should restore the scroll for all the found elements and not only window
  window.scroll(scrollX, scrollY)
})
.pre {
  height: 100vh;
}

.container {
  overflow: auto;
  height: 20px;
}

.post {
  height: 200vh;
}
<button class="btn">Move</button>
<div class="pre">

</div>
<div class="container">
  <div class="phrase-doc">Lorem ipsum bla bla</div>
  <div class="phrase-doc">Lorem ipsum bla bla</div>
  <div class="phrase-doc">Lorem ipsum bla bla</div>
  <div class="phrase-doc active">1Lorem ipsum bla bla</div>
  <div class="phrase-doc">Lorem ipsum bla bla</div>
  <div class="phrase-doc">Lorem ipsum bla bla</div>
  <div class="phrase-doc">Lorem ipsum bla bla</div>
</div>
<div class="post">

</div>

CodePudding user response:

You have to dom tag active.

document.querySelector('.btn').addEventListener('click',function (){
    var eleActive = document.querySelector('.phrase-doc.active')
    eleActive.scrollIntoView()
})

  • Related