Simple "scroll to/down" effect using minimal markup and hash tags

davecave picture davecave · May 1, 2012 · Viewed 10.8k times · Source

I am making a one page site that has a classic navigation at the top. Right now I have links set up as hash tags in order to navigate within the page:

<nav>
<a href="#about">About</a>
</nav>
...
<section id="about">...</section>

Obviously, this works but the jump to the about section is instant and not gradual. I am looking for an extremely simple implementation in order to make a gradual transition. I don't want anything fancy. No axis, offset, or any other options. I just want the scroll transition to be gradual. The only setting I want is the time it takes to finish the scroll. Also, I want to make almost no changes to my markup. I have seen several javascript plugins that require you to use anchor tags to set the locations in the html document— i don't want that. This site looks promising, but I don't know how to set it up. There is no demo so I can't see how to set it up. I am not that literate in Javascript. Also, the ScrollTo plugin for jQuery is way too complicated. I am willing to use a plugin that has a lot of options, but I just don't want the options to prevent me from figuring out how to set it up.

Any help would be much appreciated!

Answer

jacktheripper picture jacktheripper · May 1, 2012

This is the best way I have found to do it - it just uses the normal anchors but extends their functionality

$('a').click(function() {
    var elementClicked = $(this).attr("href");
    var destination = $(elementClicked).offset().top;
    $("html:not(:animated),body:not(:animated)").animate({ scrollTop: destination-15}, 500);
});

Here is a live example