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:
xxxxxxxxxx
1
var element = document.querySelector('#element');
2
3
element.scrollLeft = element.scrollWidth;
In this example, we set scrollLeft
property to scrollWidth
to scroll to the right of the element on the button click event.
xxxxxxxxxx
1
2
<html>
3
<body>
4
<div id="element" style="width: 250px; overflow-X: scroll">
5
<div style="width: 400px;">Click the button below to scroll this text...</div>
6
</div>
7
<script>
8
9
var element = document.querySelector('#element');
10
11
function scrollRight() {
12
element.scrollLeft = element.scrollWidth;
13
}
14
15
</script>
16
<button onclick="scrollRight()">Scroll to right</button>
17
</body>
18
</html>
In this example, we create a button that scrolls to the right of the element on the click event using the above solution.
xxxxxxxxxx
1
2
<html>
3
<body>
4
<div id="element" style="width: 250px; overflow-X: scroll">
5
<div style="width: 400px;">Click the button below to scroll this text...</div>
6
</div>
7
<button onclick="scrollRight()">Scroll right</button>
8
<script>
9
10
var element = document.querySelector('#element');
11
12
function scrollRight() {
13
element.scrollLeft = element.scrollWidth;
14
}
15
16
</script>
17
</body>
18
</html>