279

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>

0

13 Answers 13

601

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.

13
  • 4
    If the container has a scrollbar, you'll need to account for the scrollTop: scrollTo.offset().top - container.offset().top + container.scrollTop()
    – claviska
    Commented May 20, 2011 at 0:34
  • 1
    You can scroll the entire window with $(document).scrollTop(value) - the underlying jquery code resolves browser issues for you. Commented Jun 28, 2012 at 17:15
  • 7
    If you want scrollTo centered rather than at the top: scrollTo.offset().top - container.offset().top + container.scrollTop() - (container.height()/2)
    – Mahn
    Commented Sep 13, 2014 at 19:09
  • 8
    element.scrollIntoView() - that is all that is required. Animation is standardised. See developer.mozilla.org/en-US/docs/Web/API/Element/scrollIntoView Commented Feb 26, 2016 at 11:46
  • 11
    Note there's an "invisible" character at the very end of the code block. The character is considered invalid in Edge, chrome. - a copy-paster
    – Attacktive
    Commented Mar 24, 2017 at 2:44
118

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)
4
  • hello @infensus can you give me a working example of this cause mine is not working? i used var section2=$('#section-2'); $('html,body').animate({scrollTop: section2.offset().top});
    – anjel
    Commented Jun 19, 2013 at 9:12
  • That looks fine - are you sure section2 exists? do console.log(section2.length); and make sure it isn't 0. Will make an example in a little bit.
    – nanobar
    Commented Jun 19, 2013 at 9:45
  • Why $('html,body')? He need only in specific container. Accepted answer is better for me. I have similar case like the asked question and your answer do not worked for me.
    – Petroff
    Commented Apr 3, 2015 at 10:13
  • 3
    @Petroff strangely when I wrote this I didn't notice the element was in a scrolling container. I'll leave my answer as it is though because people come here from a Google search to scroll the body due to the question title
    – nanobar
    Commented Apr 7, 2015 at 18:41
32

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

window.scrollTo(0, $("#element").offset().top);
3
  • For something that should be so utterly simple I have spent ages on other solutions online, but this simple one liner does exactly what I need. Commented Sep 30, 2013 at 12:01
  • 3
    It should be noted, this way works for the entire window. If you want to scroll content that has overflow:scroll then this won't work.
    – Jeremy
    Commented Apr 8, 2014 at 19:38
  • I'm gonna have to try this. I solved this "scroll to an element when something is clicked" by doing it the way @lorddarq answered above with jQuery on the "html, body" selector. But the client and a co-worker are saying it's not working on first click, it seems to slightly scroll and then stop and requires multiple clicks to get it to work. I haven't been able to reproduce this on different browsers, desktop and mobile (of course), but I guess I'll try this simple method. The animated/smooth component is nice but if this method solves it I'm fine without it.
    – clamum
    Commented Aug 20, 2022 at 6:16
15

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);
});
3
  • Your one-line gist, complete with animation, was exactly what I needed. Thanks! Commented Dec 26, 2012 at 10:35
  • No need for any plugins ?? But you use jQuery! It is freaking huge library, not even a plugin.
    – Green
    Commented May 26, 2016 at 6:23
  • 2
    I ment you don't need to add a refference in addition to the jquery library reference. Plus jquery is kind of industry standard. Why would you not use it ? It's probably quite doable without jquery, but it would still require someone to write a lot of code just for the parsing part. It feels counterproductive. And it felt counterproductive to write a full on plugin just for scrolling to a measy div.
    – lorddarq
    Commented Jun 21, 2016 at 12:59
6

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

For example

row_5.scrollIntoView();
2
  • How to animate it?
    – Green
    Commented May 26, 2016 at 6:10
  • No need to animate. When you use scrollIntoView() the control will be automatically scrolled to make it display into the view.
    – Tamilarasi
    Commented Jun 29, 2016 at 14:16
4

You can use the the jQuery scrollTo plugin plugin:

$('div').scrollTo('#row_8');
1
  • 1
    the link is no more available. could you please update it.?
    – Lucky
    Commented Jul 26, 2016 at 12:06
3

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.

2

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>

2

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

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

Reference.

2
  • 6
    scrollTo requires two arguments, you have only written in one. Commented Jul 16, 2014 at 20:30
  • 2
    ... and it is called on the window object.
    – hashchange
    Commented Jul 27, 2015 at 22:19
1

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
        );
    });
1
  • @AnriëtteMyburgh im unsure if position() is functional across all browsers. Have you tried it in others to see if it works? Or can i see the code you're using and see if there's something else wrong?
    – Nlinscott
    Commented Jul 21, 2014 at 23:07
1

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.

0

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

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

        }

Not the answer you're looking for? Browse other questions tagged or ask your own question.