0

I am using the below code to auto scroll to an id after a duration.

setTimeout( function() {
   $('html, body').animate({
     'scrollTop': $('#about').offset().top
   }, 2000);
}, 3000);

However I have seen so many different ways to achieve this simple task.

It's probably too objective to ask what the best way to do this is, but I need to know if I am doing something wrong with this code. Seems to work fine in current versions of Chrome, FF and IE

Thanks in advance!

Aaron
  • 3,195
  • 5
  • 31
  • 49
  • possible duplicate of [How to scroll to specific item using jQuery?](http://stackoverflow.com/questions/2905867/how-to-scroll-to-specific-item-using-jquery) – Shaddow Jun 26 '13 at 22:57
  • maybe not exactly but idea is very similar imho – Shaddow Jun 26 '13 at 23:22

1 Answers1

2

For animation you should use delay and no need to use quotes around single string object key:

   $('html, body').delay(3000).animate({
     scrollTop: $('#about').offset().top
   }, 2000);

The .delay() method is best for delaying between queued jQuery effects. Because it is limited—it doesn't, for example, offer a way to cancel the delay—.delay() is not a replacement for JavaScript's native setTimeout function, which may be more appropriate for certain use cases.

To answer your question, no you are not doing something wrong.

A. Wolff
  • 74,033
  • 9
  • 94
  • 155
  • Hey :) in regards to the string quotations, is there any reason I should take them out other than they are not necessary or on some tiny level does it run more efficient without quotations? – Aaron Jun 26 '13 at 23:02
  • And in regards to using .delay, I am going to need some functionality, not sure what exactly. Basically there is something at the bottom of the page I want people to see as long as they are not scrolling around at the top as they are probably reading top content. But if the page is static at the top (perhaps I will incorporate mousemove) Then I will start the delay/interval – Aaron Jun 26 '13 at 23:04
  • No, nothing i'm aware of. BTW, you have to use quote for keys using kind of 'space characters' as e.g 'background-color' – A. Wolff Jun 26 '13 at 23:06
  • Thanks, I've learnt two things from you :) If you get some up votes, or duplicate answers to your answer I'll not forget you got in first! – Aaron Jun 26 '13 at 23:08