Home > OS >  Scroll not moving after adding Text with Javascript
Scroll not moving after adding Text with Javascript

Time:11-13

I'm adding some text to a textarea by using JS everytime I click on a button. The thing is that everytime the text is added, the scroll goes to top of the textarea and I don't want that. I don't want the scroll to move automatically when I add the content.

This is part of my code:

const textarea = document.getElementById('my_textarea');
let data = "new content added";
textarea.innerHTML = data   textarea.innerHTML;

Could someone please help me out?

Thanks in advance.

CodePudding user response:

I think you could just set your scroll position everytime you click on your button. So you can put this piece of code in another function and call it after your desired text is loaded.

var textarea = document.getElementById('textarea_id');
textarea.scrollTop = textarea.scrollHeight;

CodePudding user response:

Just add a particular line in your button event Listener

textarea.scrollTo(0,textarea.scrollHeight)

Overall code will look somewhat similar to this


    const textarea = document.getElementById('my_textarea');
    
    document.querySelector("button").addEventListener("click",() => {
      let data = "new content added";
      textarea.innerHTML = data   textarea.innerHTML;
      textarea.scrollTo(0,textarea.scrollHeight)
    })

  • Related