How to scroll to specific item using jQuery?

JavascriptJqueryScroll

Javascript Problem Overview


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.

div {
    width: 100px;
    height: 70px;
    border: 1px solid blue;
    overflow: auto;
}

<div>
    <table id="my_table">
        <tr id='row_1'><td>1</td></tr>
        <tr id='row_2'><td>2</td></tr>
        <tr id='row_3'><td>3</td></tr>
        <tr id='row_4'><td>4</td></tr>
        <tr id='row_5'><td>5</td></tr>
        <tr id='row_6'><td>6</td></tr>
        <tr id='row_7'><td>7</td></tr>
        <tr id='row_8'><td>8</td></tr>
        <tr id='row_9'><td>9</td></tr>
    </table>
</div>

Javascript Solutions


Solution 1 - Javascript

Dead simple. No plugins needed.

var $container = $('div'),
    $scrollTo = $('#row_8');

$container.scrollTop(
    $scrollTo.offset().top - $container.offset().top + $container.scrollTop()
);

// Or you can animate the scrolling:
$container.animate({
    scrollTop: $scrollTo.offset().top - $container.offset().top + $container.scrollTop()
});​

Here is a working example.

Documentation for scrollTop.

Solution 2 - Javascript

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)

Solution 3 - Javascript

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

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

Solution 4 - Javascript

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);
});

Solution 5 - Javascript

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

For example

row_5.scrollIntoView();

Solution 6 - Javascript

You can use the the jQuery scrollTo plugin plugin:

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

Solution 7 - Javascript

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.

Solution 8 - Javascript

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);
  });
});

$(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);
  });
});

#pane1 {
  background: #000;
  width: 400px;
  height: 400px;
}

#pane2 {
  background: #ff0000;
  width: 400px;
  height: 400px;
}

#pane3 {
  background: #ccc;
  width: 400px;
  height: 400px;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul class="nav">
  <li>
    <a href="#pane1" class=" js-scroll-to-id">Item 1</a>
  </li>
  <li>
    <a href="#pane2" class="js-scroll-to-id">Item 2</a>
  </li>
  <li>
    <a href="#pane3" class=" js-scroll-to-id">Item 3</a>
  </li>
</ul>
<div id="pane1"></div>
<div id="pane2"></div>
<div id="pane3"></div>
<!-- example of a fixed nav menu -->
<ul class="nav">
  <li>
    <a href="#pane3" class="js-scroll-to-id">Item 1</a>
  </li>
  <li>
    <a href="#pane2" class="js-scroll-to-id">Item 2</a>
  </li>
  <li>
    <a href="#pane1" class="js-scroll-to-id">Item 3</a>
  </li>
</ul>

Solution 9 - Javascript

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

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

Reference.

Solution 10 - Javascript

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
        );
    });

Solution 11 - Javascript

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][1] 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][2]. 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.][3]

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][3] 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][4]. 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][5] for that, but make sure you calculate the target position correctly if there is a border around the container.

[1]: https://stackoverflow.com/a/32046714/508355 "jQuery scroll to element - Stack Overflow" [2]: https://github.com/hashchange/jquery.scrollable "jQuery.scrollable" [3]: https://jsbin.com/kivemo/2 "Scrolling to an element in a non-window container: correct method for calculating the target position - JS Bin" [4]: https://gist.github.com/hashchange/c368ce9c642c1a70edda "hashchange/scrollTargetPosition.js | Returns the scroll target position for scrolling to the top of an element." [5]: https://stackoverflow.com/a/2906009/508355

Solution 12 - Javascript

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();

Solution 13 - Javascript

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(){
        });
              
        }

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionMisha MoroshkoView Question on Stackoverflow
Solution 1 - JavascriptJamesView Answer on Stackoverflow
Solution 2 - JavascriptDominicView Answer on Stackoverflow
Solution 3 - JavascriptFredrik StolpeView Answer on Stackoverflow
Solution 4 - JavascriptlorddarqView Answer on Stackoverflow
Solution 5 - JavascriptTamilarasiView Answer on Stackoverflow
Solution 6 - JavascriptnickfView Answer on Stackoverflow
Solution 7 - Javascriptbasti500View Answer on Stackoverflow
Solution 8 - JavascriptMD AshikView Answer on Stackoverflow
Solution 9 - JavascriptKevinView Answer on Stackoverflow
Solution 10 - JavascriptNlinscottView Answer on Stackoverflow
Solution 11 - JavascripthashchangeView Answer on Stackoverflow
Solution 12 - Javascriptmartinh_kenticoView Answer on Stackoverflow
Solution 13 - Javascriptscode2704View Answer on Stackoverflow