Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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!

like image 508
davecave Avatar asked May 01 '12 19:05

davecave


3 Answers

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

like image 102
jacktheripper Avatar answered Oct 13 '22 00:10

jacktheripper


I used straight jquery to do this.

I had a link like so ->

<a href="1" class="scrolling">Go to 1</a>

then using jquery it would scroll down to a div with another anchor with id "1"

$("a.scrolling").click(function(e) {
    e.preventDefault();
    goToByScroll($(this).attr("href"));
});

function goToByScroll(id) {
    $('html,body').animate({scrollTop: $("#"+id).offset().top},'slow');                               
}                       
like image 43
Undefined Avatar answered Oct 13 '22 00:10

Undefined


There's ScrollTo in Javascript. It's a window event. check it out here: https://developer.mozilla.org/en/DOM/window.scrollTo

like image 22
sebastien paquet Avatar answered Oct 13 '22 00:10

sebastien paquet