Chann Chann - 5 months ago 24
jQuery Question

How to move table scrollbar using js, jquery?

I have a table as follows with a horizontal scrollbar.

<table >
<tr>
<th>Col1</th>
<th>col2</th>
<th>col3</th>
<th>col4</th>
<th>col5</th>
<th>col5</th>
</tr>
</table>


enter image description here
Is there a way to move the scrollbar using javascript(dynamicaly). For example I want to move scrollbar 30px right when clicking a button.

Answer

click on right to scroll to right, and on left to scroll back.. this is an idea how it could work. Cheers.

$(".leftArrow").click(function () { 
  var leftPos = $('.wrapper').scrollLeft();
  $(".wrapper").animate({scrollLeft: leftPos - 30}, 100);
});

$(".rightArrow").click(function () { 
  var leftPos = $('.wrapper').scrollLeft();
  $(".wrapper").animate({scrollLeft: leftPos + 30}, 100);
});
.wrapper {
  width:100px;
  overflow-x: scroll;
  overflow-y: hidden;
}

table {
  width: 300px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="wrapper">
  <table>
    <tr>
      <th>Col1</th>
      <th>col2</th>
      <th>col3</th>
      <th>col4</th>
      <th>col5</th>
      <th>col5</th>
    </tr>
  </table>
</div>

<button class="leftArrow">Scroll left</button>

<button class="rightArrow">Scroll right</button>