2

I have one <div> with overflow:auto. This <div> contains a <form> with a Search bar. I am displaying the records fetched, in the same form, now all I need is to scroll the <div> (where my search results start displaying) to the top of its container <div> (and not to the top of the page).

check the jsfiddle created. http://jsfiddle.net/tusharjs/wGUE2/15/

Here, I have tried a solution I found on stackoverflow, but it scrolls the desired <div id="scrollto"> to top of page and not to the top of the <div id="maincontent">.

Thanks

2
  • check the fiddle, when you inspect the element <div id="scrollto"> you will find that, it is scrolled to top. I want its top to start from the <div id="maincontent">. Clear? Commented Jan 17, 2014 at 7:04
  • I'm very sorry that I couldn't understand. Commented Jan 17, 2014 at 7:09

1 Answer 1

7

You should use the .offset() method to get the element's actual top and subtract that from the amount to scroll.

$(document).ready( function(){
  var elem = $('#scrollto');
  if(elem)
  {
    var main = $("#maincontent"),
        t = main.offset().top;
        main.scrollTop(elem.offset().top - t);
  }
});

Here's my fork of your fiddle

It might be more impressive to animate the scroll:

main.animate({scrollTop: elem.offset().top - t}, 500);

The second parameter above is the duration in milliseconds. The updated example is here.

Sign up to request clarification or add additional context in comments.

2 Comments

Austin Mullins - your .animate() call above uses elem.offset().top but in your jsfiddle example the .animate() call uses elem.position.top()
@paparush Thanks for pointing that out. I updated the fiddle to match the answer. While playing with it, it looks like position() and offset() just happened to be returning the same values because there was nothing else on the page.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.