EN
JavaScript - safe way to scroll left of element
0
points
In this article, we would like to show you a safe way to scroll to the left of an element using JavaScript.
Practical example
This approach will work for any web browser. In older browsers, it will jump to the left immediately and in newer browsers, it will go smoothly.
// ONLINE-RUNNER:browser;
<!doctype html>
<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() {
if ('scroll' in element) {
element.scroll({
left: 0,
behavior: 'smooth'
});
} else {
element.scrollTop = 0;
}
}
</script>
<button onclick="scrollToLeft()">Scroll to left</button>
</body>
</html>