jQuery Smooth Scrolling

bntrns picture bntrns · May 11, 2012 · Viewed 13.7k times · Source

I've tried to implement smooth scrolling into an index of info. I've looked at this jsFiddle http://jsfiddle.net/9SDLw/ and I cannot get it to work. Does it matter where the code is inserted into the HTML Document or something?

Here is my code:

JS (in head of document):

<script type="text/javascript">
$('a').click(function(){
    $('html, body').animate({
        scrollTop: $( $(this).attr('href') ).offset().top
    }, 500);
    return false;
});​
</script>

Markup:

Link

<a href = "#G" rel = "" id="G" class="anchorLink">G</a><br />

Anchor

<a name = "G" id="G"><span class = "letters">G</span></a><br />

What am I missing here?

Answer

Roko C. Buljan picture Roko C. Buljan · May 11, 2012

jsBin demo

<ul id="links">
    <li><a href="#a">Go to a</a></li>
    <li><a href="#b">Go to b</a></li>
</ul>

and than somewhere in your document...

<h2 id="a">Article "a"</h2>
Lorem......
<h2 id="b">Article "b"</h2>
Lorem......

jQ:

$('#links a').click(function( e ){  
    e.preventDefault();
    var targetId = $(this).attr("href");
    var top = $(targetId).offset().top;
    $('html, body').stop().animate({scrollTop: top }, 1500);
});

what the above does is to use the retrieved anchor href and use it as jQuery's # (id) selector. Found that ID element, get it's top offset and finally animate the page.