Sven
Sven

Reputation: 53

Scroll smoothly by 100px horizontally

Heyjo,

problem: I am looking for a javascript or jQuery code since a week to get an implemented scrollbutton on my website working. The moment I fail is when the button should work multiple times: his task is not so scroll to a dedicated element, it should scroll left by, for instance, 100px. Furthermore the scrolling is supposed to happen smoothly (in other words, animated) in a proper section.

what I tried: til now I tried to fulfill this task with $('#idofsection').animate({scrollLeft: 100}, 800) but obviously it didn't work. The Problem was, one couldn't use it multiple times, it just scrolled to a position in my section. Afterwards I used javascript's scrollBy(100, 0) or scrollLeft += 100px, but unfortunately didn't got it to scroll smoothly.

I hope someone can help me because I spent so much time on this issue without finding a solution. Thanks a lot, Sven

Upvotes: 4

Views: 5671

Answers (2)

Jakub Rusilko
Jakub Rusilko

Reputation: 867

You can use scrollBy(100, 0) just like you tried and add this css property to the viewport where you want to scroll:

scroll-behavior: smooth;

.window{
  width: 200px;
  height: 100px;
  border: 1px red solid;
  overflow: hidden;
  scroll-behavior: smooth;
}
.container{
  width: 1000px;
  height: 200px;
}
.buttons{
  width: 200px;
  display: flex;
  flex-direction: row;
  justify-content: space-between;
}
<div id="window" class="window">
  <div class="container">
    fjsdlf jslkd flsakj flksad jflkjsa dlfj slakd jflskad flksdaj lfk sadlkfj asldk fslkad fjlkasd flksa jdlf jsadlkfj slkda jflksadj flksa jdlkfj sadlk jflksadj flksjadflksadj flksdaj flksdaj flksdaflksjdflk sjdalkfj skdal fjlksadj flksa fklsjadfklj sadklfj salkdjf lksadj flksjad lfkj sadlkf jslakdjf lksdaj flkasj flkjsa dlfskal flsa jdas lkfjskad fj
  </div>
</div>
<div class="buttons">
  <button onclick="document.getElementById('window').scrollBy(-100,0)">
  <-
  </button>
  <button onclick="document.getElementById('window').scrollBy(100,0)">
  ->
  </button>
</div>

Solution also here: JSFiddle

Upvotes: 4

epascarello
epascarello

Reputation: 207511

So use the animation properties += to adjust it from current position.

$("#next").click(function(){
  $('#foo').stop().animate({scrollLeft: "+=100"}, 800);
  return false;
}); 
div {
  width: 200px;
  overflow: auto;
  padding: 1em;
  border: 1px solid black;
}

div p {
  width: 1000px;
  border: 2px dashed #000;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="foo">
  <p>TEST</p>
</div>

<button id="next">Next</button>

Upvotes: 3

Related Questions