jQuery Tutorial: Scrolling Effects With Anchor Links

December 20th, 2012 Leave a comment
Like the article?
jQuery Tutorial Scrolling Effects With Anchor Links

Sometimes you’ll want to use anchor text in a page, but you don’t want any old boring anchor scroll. The instant click-through to anchor links is devoid of any interesting flair, and that’s no longer a viable option in today’s Web landscape. Web 2.0 is all about having smooth effects to go with your buttons and bevels, and so maybe you want a cool scrolling effect for your anchor links on your site. Here’s a quick and easy way to get that on your page!

Step 1: Create The Anchor Link

You’re going to want this in the part you want to link to:

<a id="scroll_click">Click here to scroll</a>
<img src="images/ourimage.png" alt="ourimage" />

You can use the scroll code for whatever you like- in this example we’re scrolling to a simple image, but you can use it for fancier types of anchoring, including a table of contents or jQuery tabs to give your website that little bit of oomph!

Step 2: Animate The Scrolling Transition

jQuery(document).ready(function() {    
  var top_pos = jQuery('#ourimage').offset().top;      
  
  jQuery('#scroll_click').click(function() {
    jQuery('html, body').animate({scrollTop:top_pos}, 'fast');
    return false;
  });
});

This code might seem a bit confusing at first – but it isn’t really! Essentially, what happens first is that we acquire the position of the image by referring to its alt. Once we’ve saved that position in top_pos, we simply pass that position to jQuery’s animate function – and the rest is done for us through jQuery’s awesome animate function! In fact, once all is said and done, the code’s not really all that difficult – the jQuery library, in a testament to its versatility, does quite a bit of the heavy lifting for us.

It’s a quick and easy way to add a cool animation to your website. You can play around with it as well – jQuery offers more options than the ones we’ve used here, which are very basic. You can visit http://api.jquery.com/animate/ to read up on the full animate tag, which includes ways to make the duration of the animation faster or slower depending on your preference as well as other different styles of effect that you can use to get your animation function looking the way you want it to look.

Help us spread the word!
  • Twitter
  • Facebook
  • LinkedIn
  • Pinterest
  • Delicious
  • DZone
  • Reddit
  • Sphinn
  • StumbleUpon
  • Google Plus
  • RSS
  • Email
  • Print
Don't miss another post! Receive updates via email!

Comment