Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery Smooth Scrolling

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?

like image 375
bntrns Avatar asked May 11 '12 17:05

bntrns


People also ask

What is smooth scrolling?

The smooth Scrolling feature for web pages allows the user to scroll smoothly while navigating across a webpage. This feature came into wide use because the normal scrolling is choppy and annoying for a lot of users who have to read long pages on the web.

How do I enable smooth scrolling in chrome?

In the address bar, type chrome://flags and press enter. In the Flags tab, search for the Smooth Scrolling setting. You can do this manually in the Available tab or use the search bar to find it. Once you've located it, press the drop-down menu next to the feature and select Enabled or Disabled.


1 Answers

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.

like image 168
Roko C. Buljan Avatar answered Oct 01 '22 01:10

Roko C. Buljan