ChatGPT解决这个技术问题 Extra ChatGPT

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.

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

1
2
3
4
5
6
7
8
9


S
Syscall

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.


If the container has a scrollbar, you'll need to account for the scrollTop: scrollTo.offset().top - container.offset().top + container.scrollTop()
You can scroll the entire window with $(document).scrollTop(value) - the underlying jquery code resolves browser issues for you.
If you want scrollTo centered rather than at the top: scrollTo.offset().top - container.offset().top + container.scrollTop() - (container.height()/2)
element.scrollIntoView() - that is all that is required. Animation is standardised. See developer.mozilla.org/en-US/docs/Web/API/Element/scrollIntoView
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
L
Luke Wenke

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)

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});
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.
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 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
F
Fredrik Stolpe

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

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

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.
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.
m
miken32

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

Your one-line gist, complete with animation, was exactly what I needed. Thanks!
No need for any plugins ?? But you use jQuery! It is freaking huge library, not even a plugin.
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.
A
Alex Jolig

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

For example

row_5.scrollIntoView();

How to animate it?
No need to animate. When you use scrollIntoView() the control will be automatically scrolled to make it display into the view.
Z
Zev Spitz

You can use the the jQuery scrollTo plugin plugin:

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

the link is no more available. could you please update it.?
S
Syscall

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.


M
MD Ashik

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


S
Syscall

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

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

Reference.


scrollTo requires two arguments, you have only written in one.
... and it is called on the window object.
N
Nlinscott

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

@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?
S
Syscall

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.


m
martinh_kentico

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

L
LBes

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

        }