2

I found numerous questions and answers here on stackoverflow about JQuery smooth scroll, but I still fail to understand how it works.

var $root = $('html, body');
$('a').click(function() {
    var href = $.attr(this, 'href');
    $root.animate({
        scrollTop: $(href).offset().top
    }, 500, function () {
        window.location.hash = href;
    });
    return false;
});
  1. Why do we select html and body not just body?
  2. animate(), animates the content of the $root variable, right?
  3. Why is an object passed to animate() function?
  4. What is scrollTop, a css property?
Oluwafemi
  • 14,243
  • 11
  • 43
  • 59
so_user
  • 333
  • 3
  • 15
  • `Smooth scroll step by step` - make each step as small as possible for smooth scroll – Jaromanda X Jan 07 '16 at 13:20
  • `Why we select html and body not just body?` Some browser(s?) implement scrolling functionality on `html`, not `body`. For the rest, check animate() doc and search for `scrollTop` (not to confuse with jQuery `scrollTop()` method) – A. Wolff Jan 07 '16 at 13:21
  • 3: The object contains the properties to be animated, and the value to animate it to. 4. scrollTop is a property of the underlying DOMElement – Rory McCrossan Jan 07 '16 at 13:23
  • **2.**: `animate` gradually changes properties of an element - in this case, only `scrollTop` (from its current value to `$(href).offset().top` in `500` ms). – Cedric Reichenbach Jan 07 '16 at 13:28
  • 1
    You should not ask multiple questions in one. Beside that **1.** is a duplicate to: [why to use 'html, body' for scrollTop instead of just 'html'](http://stackoverflow.com/questions/12222485), **3.** jQuery doc: [jQuery.animate](http://api.jquery.com/animate/#animate-properties-duration-easing-complete) `properties, An object of CSS properties and values that the animation will move toward.` **4.** `scrollTop` is a property of an DOM element [MDN: Element.scrollTop](https://developer.mozilla.org/en-US/docs/Web/API/Element/scrollTop) – t.niese Jan 07 '16 at 13:29

1 Answers1

1

To put together some answers in the comments into a response:

  1. Why to use 'html, body' for scrollTop instead of just 'html'
  2. Yes! The content of the root variable is animated - so, the scrollTop value of both html and body are changed.
  3. The three arguments passed to animate() are a new value of scrollTop, which is animated to, a duration, and a complete function. The complete function is used to update the location of the window after it's been scrolled down - it's sort of cleaning up after the scrollTop change and making sure the whole window knows "Yup, we've scrolled down".

  4. scrollTop is a property of a rendered HTML DOM object, describing how far, from the top, a certain object is scrolled down.

Community
  • 1
  • 1
Peter Smith
  • 196
  • 3