Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

105
Views
Smoothly scroll element from current position

I have written the following code to scroll an element 20 more pixels to the right.

const button = document.getElementById('slide');

button.onclick = function () {
  document.getElementById('container').scrollLeft += 20;
};

How can I make the scrolling smooth? I have tried using Element#scroll like so:

const button = document.getElementById('slide');

button.onclick = function () {
  document.getElementById('container').scroll({
      left: += 20,
      behavior: smooth
  });
};

Am I able to do this?

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

You can use Element#scrollBy to scroll a certain amount from the current position.

button.onclick = function () {
  document.getElementById('container').scrollBy({
      left: 20,
      behavior: 'smooth'
  });
};
about 4 years ago · Juan Pablo Isaza Report

0

Is this what you are looking for?

From MDN:

scrollBy() scrolls by a particular amount, whereas scroll() scrolls to an absolute position in the document.

https://developer.mozilla.org/en-US/docs/Web/API/Window/scrollBy

const container = document.querySelector("#container");
const button = document.querySelector("#btnScroll");

button.addEventListener('click', e => {
  container.scrollBy({
    left: 200,
    behavior: 'smooth'
  });
});
#container {
  position: relative;
  max-width: 200px;
  overflow-x: scroll;
  display: flex;
  margin: 20px;
}

img {
  display: inline-block
}
<div id="container">
  <img src="https://dummyimage.com/200x100/000/fff">
  <img src="https://dummyimage.com/200x100/0f0/000">
  <img src="https://dummyimage.com/200x100/00f/fff">
  <img src="https://dummyimage.com/200x100/f00/fff">
</div>
<button id="btnScroll">Scroll 200px</button>

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!