Scroll Animation for Horizontal Scroll Feature

Viewed 219

Currently I'm attempting to modify code given to me by a friend that will increase or decrease scroll distance within a div by clicking on a button on either side of the div. This is where I'm at so far -- the code I was given to link the button to the div and action is as follows:

document.addEventListener("DOMContentLoaded", function(e) {
  console.log("DOM loaded");
  var buttons = document.getElementsByClassName("right-arrow");

  for(var i = 0; i < buttons.length; i++){
    buttons[i].onclick = function(e){
      console.log(`Function fired on ${this.id}`);
      var the_scroller = this.closest(".scroller-gutter");

      the_scroller.getElementsByClassName('scroller')[0].scrollLeft += 120;
    }
  }

}, false);

All I'd really like to do is add {behavior: "smooth"} somewhere to make the onClick animation less choppy and mimic the natural scrolling behavior intended, but I'm brand new to JS and have no idea what to do.

Additionally, when I rearrange the buttons within the .scroller-gutter div, the functionality will occasionally break. Any idea why this might be?

1 Answers

You can use the scrollTo() function with behavior: 'smooth' in the options to smoothly scroll to a given point. In your case, it would look like:

the_scroller.getElementsByClassName('scroller')[0]
  .scrollTo({ left: the_scroller.getElementsByClassName('scroller')[0].scrollLeft + 120, behavior: 'smooth' });

https://codepen.io/anon/pen/VEoYyx

You can also consider using scrollBy() or scrollIntoView(), as suggested here

Related