EN
JavaScript - scroll to right of element
0
points
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>