[javascript] How to scroll to specific item using jQuery?

I have a big table with vertical scroll bar. I would like to scroll to a specific line in this table using jQuery/Javascript.

Are there built-in methods to do this?

Here is a little example to play with.

_x000D_
_x000D_
div {_x000D_
    width: 100px;_x000D_
    height: 70px;_x000D_
    border: 1px solid blue;_x000D_
    overflow: auto;_x000D_
}
_x000D_
<div>_x000D_
    <table id="my_table">_x000D_
        <tr id='row_1'><td>1</td></tr>_x000D_
        <tr id='row_2'><td>2</td></tr>_x000D_
        <tr id='row_3'><td>3</td></tr>_x000D_
        <tr id='row_4'><td>4</td></tr>_x000D_
        <tr id='row_5'><td>5</td></tr>_x000D_
        <tr id='row_6'><td>6</td></tr>_x000D_
        <tr id='row_7'><td>7</td></tr>_x000D_
        <tr id='row_8'><td>8</td></tr>_x000D_
        <tr id='row_9'><td>9</td></tr>_x000D_
    </table>_x000D_
</div>
_x000D_
_x000D_
_x000D_

This question is related to javascript jquery scroll

The answer is


I realise this doesn't answer scrolling in a container but people are finding it useful so:

$('html,body').animate({scrollTop: some_element.offset().top});

We select both html and body because the document scroller could be on either and it is hard to determine which. For modern browsers you can get away with $(document.body).

Or, to go to the top of the page:

$('html,body').animate({scrollTop: 0});

Or without animation:

$(window).scrollTop(some_element.offset().top);

OR...

window.scrollTo(0, some_element.offset().top); // native equivalent (x, y)

You can scroll by jQuery and JavaScript Just need two element jQuery and this JavaScript code :

$(function() {
  // Generic selector to be used anywhere
  $(".js-scroll-to-id").click(function(e) {

    // Get the href dynamically
    var destination = $(this).attr('href');

    // Prevent href=“#” link from changing the URL hash (optional)
    e.preventDefault();

    // Animate scroll to destination
    $('html, body').animate({
      scrollTop: $(destination).offset().top
    }, 1500);
  });
});

_x000D_
_x000D_
$(function() {_x000D_
  // Generic selector to be used anywhere_x000D_
  $(".js-scroll-to-id").click(function(e) {_x000D_
_x000D_
    // Get the href dynamically_x000D_
    var destination = $(this).attr('href');_x000D_
_x000D_
    // Prevent href=“#” link from changing the URL hash (optional)_x000D_
    e.preventDefault();_x000D_
_x000D_
    // Animate scroll to destination_x000D_
    $('html, body').animate({_x000D_
      scrollTop: $(destination).offset().top_x000D_
    }, 1500);_x000D_
  });_x000D_
});
_x000D_
#pane1 {_x000D_
  background: #000;_x000D_
  width: 400px;_x000D_
  height: 400px;_x000D_
}_x000D_
_x000D_
#pane2 {_x000D_
  background: #ff0000;_x000D_
  width: 400px;_x000D_
  height: 400px;_x000D_
}_x000D_
_x000D_
#pane3 {_x000D_
  background: #ccc;_x000D_
  width: 400px;_x000D_
  height: 400px;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<ul class="nav">_x000D_
  <li>_x000D_
    <a href="#pane1" class=" js-scroll-to-id">Item 1</a>_x000D_
  </li>_x000D_
  <li>_x000D_
    <a href="#pane2" class="js-scroll-to-id">Item 2</a>_x000D_
  </li>_x000D_
  <li>_x000D_
    <a href="#pane3" class=" js-scroll-to-id">Item 3</a>_x000D_
  </li>_x000D_
</ul>_x000D_
<div id="pane1"></div>_x000D_
<div id="pane2"></div>_x000D_
<div id="pane3"></div>_x000D_
<!-- example of a fixed nav menu -->_x000D_
<ul class="nav">_x000D_
  <li>_x000D_
    <a href="#pane3" class="js-scroll-to-id">Item 1</a>_x000D_
  </li>_x000D_
  <li>_x000D_
    <a href="#pane2" class="js-scroll-to-id">Item 2</a>_x000D_
  </li>_x000D_
  <li>_x000D_
    <a href="#pane1" class="js-scroll-to-id">Item 3</a>_x000D_
  </li>_x000D_
</ul>
_x000D_
_x000D_
_x000D_


I agree with Kevin and others, using a plugin for this is pointless.

window.scrollTo(0, $("#element").offset().top);

I managed to do it myself. No need for any plugins. Check out my gist:

// Replace #fromA with your button/control and #toB with the target to which     
// You wanna scroll to. 
//
$("#fromA").click(function() {
    $("html, body").animate({ scrollTop: $("#toB").offset().top }, 1500);
});

Contrary to what most people here are suggesting, I'd recommend you do use a plugin if you want to animate the move. Just animating scrollTop is not enough for a smooth user experience. See my answer here for the reasoning.

I have tried a number of plugins over the years, but eventually written one myself. You might want to give it a spin: jQuery.scrollable. Using that, the scroll action becomes

$container.scrollTo( targetPosition );

But that's not all. We need to fix the target position, too. The calculation you see in other answers,

$target.offset().top - $container.offset().top + $container.scrollTop()

mostly works but is not entirely correct. It doesn't handle the border of the scroll container properly. The target element is scrolled upwards too far, by the size of the border. Here is a demo.

Hence, a better way to calculate the target position is

var target = $target[0], 
    container = $container[0];

targetPosition = $container.scrollTop() + target.getBoundingClientRect().top - container.getBoundingClientRect().top - container.clientTop;

Again, have a look at the demo to see it in action.

For a function which returns the target position and works for both window and non-window scroll containers, feel free to use this gist. The comments in there explain how the position is calculated.

In the beginning, I have said it would be best to use a plugin for animated scrolling. You don't need a plugin, however, if you want to jump to the target without a transition. See the answer by @James for that, but make sure you calculate the target position correctly if there is a border around the container.


Scroll element to center of container

To bring the element to the center of the container.

DEMO on CODEPEN

JS

function scrollToCenter() {
  var container = $('.container'),
    scrollTo = $('.5');

  container.animate({
    //scrolls to center
    scrollTop: scrollTo.offset().top - container.offset().top + scrollTo.scrollTop() - container.height() / 2
  });
}

HTML

<div class="container">
   <div class="1">
    1
  </div>
  <div class="2">
    2
  </div>
  <div class="3">
    3
  </div>
  <div class="4">
    4
  </div>
  <div class="5">
    5
  </div>
  <div class="6">
    6
  </div>
  <div class="7">
    7
  </div>
  <div class="8">
    8
  </div>
  <div class="9">
    9
  </div>
  <div class="10">
    10
  </div>


</div>
<br>
<br>
<button id="scroll" onclick="scrollToCenter()">
  Scroll
</button>

css

.container {
  height: 60px;
  overflow-y: scroll;
  width 60px;
  background-color: white;
}

It is not exact to the center but you will not recognice it on larger bigger elements.


I did a combination of what others have posted. Its simple and smooth

 $('#myButton').click(function(){
        $('html, body').animate({
            scrollTop: $('#scroll-to-this-element').position().top },
            1000
        );
    });

You can use scrollIntoView() method in javascript. just give id.scrollIntoView();

For example

row_5.scrollIntoView();

For what it's worth, this is how I managed to achieve such behavior for a general element which can be inside a DIV with scrolling (without knowing the container)

It creates a fake input of the height of the target element, and then puts a focus to it, and the browser will take care about the rest no matter how deep within the scrollable hierarchy you are. Works like a charm.

var $scrollTo = $('#someId'),
inputElem = $('<input type="text"></input>');

$scrollTo.prepend(inputElem);
inputElem.css({
  position: 'absolute',
  width: '1px',
  height: $scrollTo.height()
});
inputElem.focus();
inputElem.remove();

You can use the the jQuery scrollTo plugin plugin:

$('div').scrollTo('#row_8');

Not sure why no one says the obvious, as there's a built in javascript scrollTo function:

scrollTo( $('#element').position().top );

Reference.


I did this combination. its work for me. but facing one issue if click move that div size is too large that scenerio scroll not down to this particular div.

 var scrollDownTo =$("#show_question_" + nQueId).position().top;
        console.log(scrollDownTo);
        $('#slider_light_box_container').animate({
            scrollTop: scrollDownTo
            }, 1000, function(){
        });

        }

Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to jquery

How to make a variable accessible outside a function? Jquery assiging class to th in a table Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Getting all files in directory with ajax Bootstrap 4 multiselect dropdown Cross-Origin Read Blocking (CORB) bootstrap 4 file input doesn't show the file name Jquery AJAX: No 'Access-Control-Allow-Origin' header is present on the requested resource how to remove json object key and value.?

Examples related to scroll

How to window.scrollTo() with a smooth effect Angular 2 Scroll to bottom (Chat style) Scroll to the top of the page after render in react.js Get div's offsetTop positions in React RecyclerView - How to smooth scroll to top of item on a certain position? Detecting scroll direction How to disable RecyclerView scrolling? How can I scroll a div to be visible in ReactJS? Make a nav bar stick Disable Scrolling on Body