tushar.dahiwale
tushar.dahiwale

Reputation: 138

scroll within div using jquery

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

Upvotes: 2

Views: 10323

Answers (1)

Austin Mullins
Austin Mullins

Reputation: 7437

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.

Upvotes: 7

Related Questions