How to add smooth scrolling effect on horizontal scrolling?

Viewed 286

I just saw an answer by Vlad Danila, but can't reproduce the smooth scrolling effect. Can anyone help me?

Here's an example code snippet I put together:

const buttonRight = document.getElementById('slideRight');
const buttonLeft = document.getElementById('slideLeft');

buttonRight.onclick = function() {
  document.getElementById('container').scrollLeft += 20;
};
buttonLeft.onclick = function() {
  document.getElementById('container').scrollLeft -= 20;
};
#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>

Thanks in advance!

1 Answers

You can use the native CSS property scroll-behavior: smooth, like so:

const buttonRight = document.getElementById('slideRight'); const buttonLeft = document.getElementById('slideLeft');

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

#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>

The only downside is that in Safari it only works with a flag (Ref). To overcome that you can use a ponyfill.

Related