17

I have this code snippet which scrolls the entire body to a particular location →

$('html, body').animate({ scrollTop: 1000}, 800, 'swing');

But what if i want to scroll to a particular location within a div like this →

$('#div-id').animate({ scrollTop: 1000}, 800, 'swing');

I tried this way but its not working, can you tell me where i am going wrong?

NOTE: The element #div-id has overflow:auto as one of its css rule.

2
  • 2
    Is the div scrollable? overflow-y: scroll;?
    – DGS
    Commented Aug 31, 2013 at 6:58
  • The plugin for which I asked this question is now being used by many developers, may be worth a look: plugins.compzets.com/animatescroll
    – Ram Patra
    Commented Jun 27, 2016 at 13:36

2 Answers 2

30

Try this demo:

$('#div').scroll();
$("#div").animate({
  scrollTop: 1000
}, 2000);
#div {
  height: 100px;
  overflow: scroll;
  width: 200px;
  border: 2px solid red;
}
<!DOCTYPE html>
<html>

<body>
  <div id='div'>
    dads dads dads dadsdads dadsdads dadsdads dadsdads dadsdads dadsdads dads dads dadsdads dadsdads dadsdads dadsdads dadsdads dadsdads dads dads dadsdads dadsdads dadsdads dadsdads dadsdads dadsdads dads dads dadsdads dadsdads dadsdads dadsdads dadsdads
    dadsdads dads dads dadsdads dadsdads dadsdads dadsdads dadsdads dadsdads dads dads dadsdads dadsdads dadsdads dadsdads dadsdads dadsdads dadsdads dadsdads dadsdads dadsdads dadsdads dadsdads dadsdads dads dads dadsdads dadsdads dadsdads dadsdads dadsdads
    dadsdads dadsdads dadsdads dadsdads dadsdads dadsdads dadsdads dadsdads dads
  </div>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
</body>

</html>

2
  • 8
    Thanks for the answer, this works for me but i don't understand why you call the scroll() function and then again animate(), it can be done directly with animate() i guess
    – Ram Patra
    Commented Aug 31, 2013 at 7:41
  • 1
    for nice look and user a easy to understand it what happen on it Commented Aug 31, 2013 at 10:37
10

How about trying like this:-

function scrollingdiv(parentid, id){
    $("#"+parentid).animate({scrollTop: $("#"+id).position().top}, 800, 'swing');
}
0

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.