Home > OS >  Automatic scroll to bottom of page doesnt work [javascript]
Automatic scroll to bottom of page doesnt work [javascript]

Time:10-18

I'm attempting to create a terminal/console on my website. I found the functions for scrolling down on a page using javascript, which are window.scrollTo(0,document.body.scrollHeight); and window.scrollTo(0,document.querySelector(".fakeScreen").scrollHeight). However, I can make neither of them work. I put them on different places; at the bottom of my writeText function and at each of my functions, however none worked.

Showcase

Attempt one (writeText function):

function writeText(data) {
    output.innerHTML  = `${data}<br>`;
    window.scrollTo(0,document.body.scrollHeight);
}

Attempt two (at each of my functions):

function whoami() {
    writeText(`
<br>
hi! i'm gxzs, bla bla bla..
<br>`)
window.scrollTo(0,document.body.scrollHeight);
}

Css (terminal, scrollbar)

.terminalScreen {
    background-color: #282828;
    opacity: 90%;
    box-sizing: border-box;
    position: relative;
    width: 100%;
    height: 100%;
    overflow-y: scroll;
    width: 1500px;
    height: 800px;
    margin: 0 auto;
    padding: 20px;
    vertical-align: center;
}

.terminalScreen::-webkit-scrollbar {
    width: 12px;              
}

.terminalScreen::-webkit-scrollbar-track {
    background: #282828;        
}

.terminalScreen::-webkit-scrollbar-thumb {
    background-color: #141414;    
    border-radius: 15px;       
    border: 3px solid #282828;  
}
.terminalScreen .output {
    width: 100%;
    color: #fff;
    font-size: 14pt;
    font-family: 'Roboto Mono', monospace;
}

CodePudding user response:

The window object you are targeting is the window object exposed by the browser and not the terminal window.

To scroll the terminal scrollbar you need to target the element with the scrollbar inside the terminal. Like this:

document.querySelector(".terminalScreen").scrollTo(0, document.body.scrollHeight)
  • Related