1

Description

I want to call a function after the javascript .scroll() function has finished.

Code

The interesting part is the javascript:

const vertScroll = document.getElementById('boxSlider');

$("#btnLeft").on("click", () => {
        vertScroll.scroll({
            left: vertScroll.scrollLeft - 120,
            behavior: "smooth"
        });
        
        //This should print out the new value of 
        //vertScroll but instead always prints the value
        //before scroll()
        console.log(vertScroll.scrollLeft);
});
     
$("#btnRight").on("click", () => {
        vertScroll.scroll({
            left: vertScroll.scrollLeft + 120,
            behavior: "smooth"
        });
        
        //same as above
        console.log(vertScroll.scrollLeft);
});
.boxSlider {
  width: 100%;
  overflow-x: auto;
  white-space: nowrap;
  display: inline-block;
}

.box {
  display: inline-block;
  background-color: cyan;
  width: 100px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="boxSlider" class="boxSlider">
  <div class="box">Box 1</div>
  <div class="box">Box 2</div>
  <div class="box">Box 3</div>
  <div class="box">Box 4</div>
  <div class="box">Box 5</div>
  <div class="box">Box 6</div>
  <div class="box">Box 7</div>
  <div class="box">Box 8</div>
  <div class="box">Box 9</div>
  <div class="box">Box 10</div>
</div>

<input id="btnLeft" type="Button" value="Scroll left"/>
<input id="btnRight" type="Button" value="Scroll right" />

Expected Behaviour

console.log(...) should output the scroll value after the scroll() function has completed.

Not the answer

Don't just do console.log(scrollLeft - 120) (or +120) since I want to implement more complex code there and the console.log() is just for better understanding.

What I've tried

I've looked at the scroll() docs (mozilla scroll()) and it doesn't seem to have a callback function.

Question

How can I achieve the expected behaviour?

TIA

0 Answers0