Scrolling jQuery Smooth

I tried to implement smooth scrolling into the information index. I 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 else?

Here is my code:

JS (in the title of the 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?

+7
source share
2 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 anywhere else 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 is stated above is to use the extracted href anchor and use it as a jQuery # (id) selector. This ID element is found, return it up offset and finally leave the page.

+10
source

You have to wrap all your code with

 $(document).ready(function(){ ... }); 

or simply

 $(function(){ ... }); 
-one
source

All Articles