'How to scroll left-right with buttons with javascript smoothly?

I use this code to scroll my div content with left and right buttons. This simple code is very useful I can use it anywhere. So I just need to know how to scroll when these buttons smoothly. By editing this piece of javascript code can I scroll smoothly when I click the buttons?

const buttonRight = document.getElementById('slideRight');
        const buttonLeft = document.getElementById('slideLeft');
    
        buttonRight.onclick = function () {
          document.getElementById('container').scrollLeft += 150;
        };
        buttonLeft.onclick = function () {
          document.getElementById('container').scrollLeft -= 150;
        };
#container {
      width: 145px;
      height: 100px;
      border: 1px solid #ccc;
      overflow-x: scroll;
    }

    #content {
      width: 250px;
      background-color: #ccc;
    }
<div id="container">
      <div id="content">Click the buttons to slide horizontally!</div>
    </div>
    <button id="slideLeft" type="button">Slide left</button>
    <button id="slideRight" type="button">Slide right</button>


Solution 1:[1]

You can use css scroll-behavior: smooth; on the container element:

const rightButtons = Array.from(document.getElementsByClassName('slideRight'));
const leftButtons = Array.from(document.getElementsByClassName('slideLeft'));
const containers = Array.from(document.getElementsByClassName('container'));

let index = 0;
for (const rightButton of rightButtons) {
    const container = containers[index];
    rightButton.addEventListener("click", function () {
        container.scrollLeft += 150;
    });
    index++;
}

index = 0;
for (const leftButton of leftButtons) {
    const container = containers[index];
    leftButton.addEventListener("click", function () {
        container.scrollLeft -= 150;
    });
    index++;
}
.container {
  width: 145px;
  height: 100px;
  border: 1px solid #ccc;
  overflow-x: scroll;
  scroll-behavior: smooth;
}

.content {
  width: 250px;
  background-color: #ccc;
}
<div class="container">
  <div class="content">Click the buttons to slide horizontally!</div>
</div>
<button class="slideLeft" type="button">Slide left</button>
<button class="slideRight" type="button">Slide right</button>

<div class="container">
  <div class="content">Click the buttons to slide horizontally!</div>
</div>
<button class="slideLeft" type="button">Slide left</button>
<button class="slideRight" type="button">Slide right</button>

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1