Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to scroll an item inside a scrollable div to the top

Tags:

jquery

I have a #contact-list-scroller div that scrolls in the page. Based on a contact_XXXX ID I'd like the #contact-list-scroller scroll position to bet set to make sure the contact_XXX item is at the top of the page.

<div id="contact-list-scroller">
   <div id="contact_8965">stuff</div>
   <div id="contact_8966">stuff</div>
   <div id="contact_8967">stuff</div>
   <div id="contact_8968">stuff</div>
   <div id="contact_8969">stuff</div>
   .....
</div>

Here's what I have so far:

$('#contact-list-scroller').scrollTop($('#contact_' + id).scrollTop());

But that is just scrolling to the top. Ideas? Thanks

like image 452
AnApprentice Avatar asked May 01 '11 05:05

AnApprentice


People also ask

How do I scrollTo the element inside a scrollable div?

onclick = function () { console. log('click') scrollTo(document. getElementById('container'), topPos-10, 600); } function scrollTo(element, to, duration) { var start = element. scrollTop, change = to - start, currentTime = 0, increment = 20; var animateScroll = function(){ currentTime += increment; var val = Math.

How do you scroll with elements?

scroll() The scroll() method of the Element interface scrolls the element to a particular set of coordinates inside a given element.

How do you scrollTo the top in React?

Use the window. scrollTo() method to scroll to the top of the page in React, e.g. window. scrollTo(0, 0) . The scrollTo method on the window object scrolls to a particular set of coordinates in the document.


3 Answers

I think you'll need position().top. Because the values returned by position() are relative to its parent (unlike offset()), it makes your code more flexible. If you change the position of your parent container your code won't break.

Example:

var contactTopPosition = $("#contact_8967").position().top;
$("#contact-list-scroller").scrollTop(contactTopPosition);

or animated:

$("#contact-list-scroller").animate({scrollTop: contactTopPosition});

See jsfiddle: http://jsfiddle.net/5zf9s/

like image 160
Richard Avatar answered Oct 14 '22 08:10

Richard


Even I was having same situation and wanted to scroll element to top. Now, there is direct support for this behavior.

Just use <element>.scrollIntoView(true) JavaScript method.


Example:

document.getElementById("yourElementId").scrollIntoView(true);


More Info:

Although this is experimental now, soon will get support in every browser. You could find more info on this at : MDN

like image 37
Kedar.Aitawdekar Avatar answered Oct 14 '22 08:10

Kedar.Aitawdekar


After trying all of the above with no success I found this at W3schools:

var elmnt = document.getElementById("Top");
elmnt.scrollIntoView();
like image 34
ivan Avatar answered Oct 14 '22 09:10

ivan