Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

scrollLeft animation - clean vanilla JS

I have a question , there is possible to add animation to scrollLeft in clean vanilla JS ?

I added container with overflow:scroll and after click scrollLeft is scrolling + 100, but with no animation :(

To test it please wrap window to mobile view.

Here is the link to my codepen:

**https://codepen.io/pawel_wojkiewicz/pen/YzyBQvj**
like image 569
pwo Avatar asked Jun 06 '26 07:06

pwo


2 Answers

Element.scroll() has a behavior option which can be set to smooth

document.querySelector('.box').addEventListener('click', function () {
    this.scroll({
        left: 0,
        top: 0,
        behavior: 'smooth'
    })
});
.box {
    width: 300px;
    overflow-x: scroll;
    background-color: #eeeeee;
    padding: 20px;
}

.box .text {
    width: 500px;
    display: block;
    font-size: 30px;
}
<div class="box"><span class="text">this textbox scrolls to the left smoothly when clicked.</span></div>
like image 168
Sev Avatar answered Jun 07 '26 20:06

Sev


you can use scrollBy together with smooth behavior:

document.querySelector('.box').addEventListener('click', function () {
    this.scrollBy({
        left: 100,
        top: 0,
        behavior: 'smooth'
    })
});
like image 31
T.B.S Avatar answered Jun 07 '26 20:06

T.B.S