1

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.

2

2 Answers 2

2

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>

Sign up to request clarification or add additional context in comments.

Comments

1

You can use the element.scrollLeft = 30px method in javascript. So for example if your table's ID is "table", you could say :

table = document.getElementById("table")
function scroll_right(){
    table.scrollLeft = 30px
}

And then if you want to have a button in html that scrolls to the right :

<button onclick="scroll_right">Scroll right</button>

2 Comments

this method is used to scroll the window, isn't it? I only need to scroll the table
Well in that case you can use element.scrollLeft = 30px, I changed the answer above to give you an example

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.