Scroll a div automatically using CSS overflow

Asked

Viewed 59 times

-3

I made a type of typeWrite(typewriter), with html css and javascript. I put an overflow: scroll on my div where when she breaks the line I wanted the scroll to kind of accompany the content ,without me having to scroll to it .

In short : I want that when it reaches the limit of this div , somehow it would automatically follow the text without me having to scroll with my mouse .

Essa é a div que esta com o overflow: scroll

//CSS
.display {
    width: 30rem;
    height: 3rem;
    border: 1px solid white;
    background-color: white;
    margin-top: 180px;
    padding: 0px 30px 40px 30px;
    border-radius: 10px;
    text-align: center;
    font-size: 24px;
    word-break: break-all;
    overflow: hidden;
    overflow-y:scroll;
    min-height: 50px;
}
//HTML
 <div class="display" id="tela"> </div>

1 answer

2

You must use the property element.scrollTop and every time a character is inserted div and arrow the scrollTop from her to her size.

Docs: https://developer.mozilla.org/en-US/docs/Web/API/Element/scrollTop

var i = 0;
var objDiv = document.getElementById("tela");
var txt = 'Inicio kkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkk meio kkkkkkkkkkkkkkkkkkkkkk Fim';
var velocidade = 50;

function typeWriter() {
  if (i < txt.length) {
    objDiv.innerHTML += txt.charAt(i);
    i++;
    //Seta o scroll da div para o tamanho dela proria
    objDiv.scrollTop = objDiv.scrollHeight;
    setTimeout(typeWriter, velocidade);
  }
}

typeWriter();
body {
  background: black;
}
.display {
    width: 30rem;
    height: 3rem;
    border: 1px solid white;
    background-color: white;
    margin: 0 auto;
    margin-top: 50px;
    border-radius: 10px;
    text-align: center;
    font-size: 24px;
    word-break: break-all;
    overflow: hidden;
    overflow-y:scroll;
    min-height: 50px;
}
<div class="display" id="tela"></div>

  • I found show the way you did. But tbm found only 1 command that does what I wanted it to be screen.scrollTop = screen.scrollHeight; . in this command the bar always gets down was basically what I wanted . But I’ll delete the one I did and I’ll do it in your obg way

Browser other questions tagged

You are not signed in. Login or sign up in order to post.