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.
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.
xxxxxxxxxx
1
2
<html>
3
<body>
4
<div id="element" style="width: 250px; overflow-X: scroll">
5
<div style="width: 400px;">Scroll this text to the right and click the button...</div>
6
</div>
7
<script>
8
9
var element = document.querySelector('#element');
10
11
function scrollToLeft() {
12
if ('scroll' in element) {
13
element.scroll({
14
left: 0,
15
behavior: 'smooth'
16
});
17
} else {
18
element.scrollTop = 0;
19
}
20
}
21
22
</script>
23
<button onclick="scrollToLeft()">Scroll to left</button>
24
</body>
25
</html>