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 O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.