0

I am following this post.

Scroll to the center of viewport

I do like the answer but when I use it, I got an error in my console.

  $('body').animate({
      scrollTop: $(this).offset().top - ($(window).height()-$(this).outerHeight(true)) / 2
  }, 5000);

The error:

Uncaught TypeError: Cannot read property 'top' of undefined

I am not sure why $(this).offset() is undefined. Can anyone help me about it?

Thanks!

Community
  • 1
  • 1
FlyingCat
  • 14,036
  • 36
  • 119
  • 198

2 Answers2

2

Instead of using $(this), use $('body').offset() instead. Looks like $(this) is referring to the window object which has no offset property.

Joel
  • 2,227
  • 1
  • 17
  • 23
  • Interesting, how could that possibly be when the OP is using `$('body')` explicitly in the outer call? – Ruan Mendes Feb 04 '14 at 17:49
  • 1
    I looked a bit into the jQuery source, and it appears that the animation is being run using setTimeout in the context of the window and not the selector, though I could be wrong, it's a pretty complex library to step through. This appears to be the case though. – Joel Feb 04 '14 at 17:56
  • I think I see, it's because the call to `$(this)` is not inside of a function, so this is the `window`. I was thinking when you pass a function to `$.on` and that within there, this is the current element – Ruan Mendes Feb 04 '14 at 21:33
1

You need to mention what "this" stands for. In the post you mention, they are using the 'img' tag. Use this instead:

$( document ).ready(function() {
    $('body').animate({ scrollTop: $('body').offset().top - ( $(window).height() - $(this).outerHeight(true) ) / 2  }, 500);
});

Also, you might want to change the 5000 at the end to a smaller number. Else it will take 5 seconds to scroll to the center of the page.

Community
  • 1
  • 1
CodeWalker
  • 98
  • 7