4

I cannot get this to scroll correctly to the bottom of a DIV when I push a new line to it. It scrolls down to the bottom, EXCEPT for the very last line and I have no idea why. Things I have tried:

var objDiv = document.getElementById("gameArea");
objDiv.scrollTop = objDiv.scrollHeight;

and

var objDiv = document.getElementById("gameArea");
objDiv.scrollTop = objDiv.scrollHeight - objDiv.clientHeight;

I also tried the scrollIntoView() for the bottom inputted line class but that didn't work either.

Full function:

pushText(input : string) {
    this.inputs.push(input)
    var objDiv = document.getElementById("gameArea");
    objDiv.scrollTop = objDiv.scrollHeight - objDiv.clientHeight;
  }

HTML is as follows:

<div class="mb-3" style="width: 70%; margin:auto;">
  <label for="gameArea" class="form-label">Escape!</label>
  <div class="form-control" id="gameArea">
    <div class="read" *ngFor="let i of this.inputs">{{i}}</div>
  </div>
  <form [formGroup]="formgroup" (ngSubmit)="update()">
  <input class="form-control input" type="text" formControlName="input" [ngStyle]="formgroup.controls.input.invalid && formgroup.controls.input.touched ? {'border': 'red solid 2px'} : {'border':'none'}" required placeholder="Type here, player." aria-label="type here">
  <button class="btn btn-primary" [disabled]="formgroup.controls.input.invalid" type="submit">Submit</button>
</form>
</div>

CSS:

#gameArea {
  background-color:#fff;
  height: 300px;
  overflow: scroll;
}
3
  • 3
    You haven't provided the code where you push your new line and then call your scroll update, so this is just an idea. Maybe when you adjust scrollTop your UI hasn't updated yet with the new line. You could try to wait until the UI updates, a simple trick for this would be to wrap your code inside a setTimeout function. Commented Aug 20, 2021 at 14:03
  • @westefan Oh my gosh you were right. The setTimeout worked for it. Added the full function above though and I just figured it was running line by line. Commented Aug 20, 2021 at 14:11
  • 1
    sounds like someone has the opportunity to answer their own question :) Commented Aug 20, 2021 at 14:12

1 Answer 1

3

Per @westfan's comment this is what worked! :

setTimeout(() => {
  var objDiv = document.getElementById("gameArea");
  objDiv.scrollTop = objDiv.scrollHeight;
},0)

UI wasn't updating in time before the scrolling would run.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.