Languages
[Edit]
EN

JavaScript - scroll to right of element

0 points
Created by:
Violetd
925

In this article, we would like to show you how to scroll to the right of an element using JavaScript.

Quick solution:

var element = document.querySelector('#element');

element.scrollLeft = element.scrollWidth;

 

1. Using scrollLeft property

In this example, we set scrollLeft property to scrollWidth to scroll to the right of the element on the button click event.

// ONLINE-RUNNER:browser;

<!doctype html>
<html>
<body>
  <div id="element" style="width: 250px; overflow-X: scroll">
    <div style="width: 400px;">Click the button below to scroll this text...</div>
  </div>
  <script>

    var element = document.querySelector('#element');

    function scrollRight() {
        element.scrollLeft = element.scrollWidth;
    }

  </script>
  <button onclick="scrollRight()">Scroll to right</button>
</body>
</html>

2. Scroll to the right on click

In this example, we create a button that scrolls to the right of the element on the click event using the above solution.

// ONLINE-RUNNER:browser;

<!doctype html>
<html>
<body>
  <div id="element" style="width: 250px; overflow-X: scroll">
    <div style="width: 400px;">Click the button below to scroll this text...</div>
  </div>
  <button onclick="scrollRight()">Scroll right</button>
  <script>

    var element = document.querySelector('#element');

    function scrollRight() {
        element.scrollLeft = element.scrollWidth;
    }

  </script>
</body>
</html>

 

References

  1. Element.scrollLeft - Web APIs | MDN
  2. Element.scrollWidth - Web APIs | MDN
  3. Element.scroll() - Web APIs | MDN
  4. Element.scrollTo() - Web APIs | MDN

Alternative titles

  1. JavaScript - scroll to right of element on click event
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join