Search code examples
javascriptscroll

Javascript: scrollBy function executed on a div


I have a div with overflow: scroll; And I would like to put a button. When you press it, the content of the div scrolls.

Something like:

function scrollDiv() {
  document.getElementById("d").scrollBy(100, 100);
}
<div id="d">
  <p>Click the button to scroll by 100px.</p>
  <button onclick="scrollDiv()">Click me to scroll!</button>
</div>

This works in FF, but not in Chrome. In Chrome I get

Uncaught TypeError: undefined is not a function

The scrollBy function seems to be defined as window function, so I guess this is the problem, and it's working in FF not by standard.

But is there another way to do that? I am not using jQuery, and I'd rather not.


Solution

  • You can try this:

    function scrollDiv(){
        document.getElementById("d").scrollTop += 100;
        document.getElementById("d").scrollLeft += 100;
    }