Reputation: 172
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;
}
Upvotes: 4
Views: 6788
Reputation: 172
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.
Upvotes: 3