Time for action – animating the scroll

The script itself is relatively straight-forward too. Add the following code to the empty function at the bottom of the HTML file:

var parent = document.getElementById("post"),
  speed = 7,
  win = $(window);

$("nav a", parent).click(function(e) {

  e.preventDefault();

  var target = $(this).attr("href"),
    offset = $(target).offset(),
    newScroll = 0,
    maxScroll = document.body.scrollHeight;

    while (newScroll < offset.top && win.scrollTop() < maxScroll) {

      win.scrollTop(newScroll);
      newScroll = newScroll + speed;
    }
  });

$(".top", parent).click(function(e) {

  e.preventDefault;

  var newScroll = win.scrollTop();

  while (newScroll > 0 && win.scrollTop() > 0) {

    win.scrollTop(newScroll);
    newScroll = newScroll - speed;
  }
});

Save the ...

Get jQuery 1.4 Animation Techniques Beginner's Guide now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.