Search code examples
javascriptscrolltextarea

Scroll not moving after adding Text with Javascript


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.


Solution

  • 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)
        })