JavaScript - scroll to left of element
In this article, we would like to show you how to scroll to the left of an element using JavaScript.
Quick solution:
xxxxxxxxxx
var element = document.querySelector('#element');
element.scrollLeft = 0;
Note:
Go to this article if you're looking for a solution that works in both modern and older browsers.
In this example, we set scrollLeft
property to 0
to scroll to the left of the element on the button click event.
xxxxxxxxxx
<html>
<body>
<div id="element" style="width: 250px; overflow-X: scroll">
<div style="width: 400px;">Scroll this text to the right and click the button...</div>
</div>
<script>
var element = document.querySelector('#element');
function scrollToLeft() {
element.scrollLeft = 0;
}
</script>
<button onclick="scrollToLeft()">Scroll to left</button>
</body>
</html>
In this example, we use scroll()
/ scrollTo()
methods to scroll to the left of the element on the button click event.
Note:
The
scroll()
/scrollTo()
methods appeared in major web browsers around 2015-2020.
xxxxxxxxxx
<html>
<body>
<div id="element" style="width: 250px; overflow-X: scroll">
<div style="width: 400px;">Scroll this text to the right and click the button...</div>
</div>
<script>
var element = document.querySelector('#element');
function scrollToLeft() {
element.scroll(0, element.scrollTop);
// or:
// element.scrollTo(0, element.scrollTop);
}
</script>
<button onclick="scrollToLeft()">Scroll to left</button>
</body>
</html>
In this example, we use scroll()
/ scrollTo()
methods with smooth
behavior to scroll to the left of the element on the button click event.
Note:
The
scroll()
/scrollTo()
methods appeared in major web browsers around 2015-2020.
xxxxxxxxxx
<html>
<body>
<div id="element" style="width: 250px; overflow-X: scroll">
<div style="width: 400px;">Scroll this text to the right and click the button...</div>
</div>
<script>
var element = document.querySelector('#element');
function scrollToLeft() {
element.scroll({
left: 0,
behavior: 'smooth'
});
// or:
// element.scrollTo({
// left: 0,
// behavior: 'smooth'
// });
}
</script>
<button onclick="scrollToLeft()">Scroll to left</button>
</body>
</html>