Smooth Scroll with jQuery

Every now and then I get some really cool feature request, nothing too big – just something simple yet effective. Anchor links aren’t talked about much these days but they’re so useful in situations where you run into a really long website with a lot of content (or anything), you have to keep scrolling down just to get to the footer. Worse yet, what if the contact form is down at the footer – that’s a lot of wasted time, space and potential customers lost. Not a good thing.

The solution and probably the most simple and effective way is to add an anchor link. This can easily be done with plain HTML.


<a class="scrollContact" href="#scrollContact" title="Fill Out Our Contact Form!">Fill Out Our Contact Form!</a>

<div id="scrollContact">
// Contact form here
</div>

So when a visitor clicks on that hyperlink, the page will immediately “leapfrog” down to the contact form way down at the footer. Pretty neat.

In my situation though, I used jQuery to dynamically create the element and attach some cool scrolling effect to it. Their templating system was a little restrictive, so I’m glad jQuery came to the rescue.


jQuery(document).ready(function() {

  jQuery(".custom-featured-img").append('<a class="scrollContact" href="#scrollContact" title="Fill Out Our Contact Form!">Fill Out Our Contact Form!</a>');

    jQuery(".scrollContact").click(function(e) {
	e.preventDefault();
	
        jQuery("html, body").animate({ scrollTop: jQuery(jQuery(this).attr("href")).offset().top }, 500);
   });
   
});

To break it down, I injected an anchor link element within a div containing “.custom-featured-img” so I can position it absolute. This way I can have more control on it’s positioning relative to its parent element – “.custom-featured-img”.

Using jQuery I use the append method to do that which I just described, which is the same thing as appending an element.

Then using the click method, I attached this event handler to the anchor link itself and within the function call we prevent the default click behavior from firing by calling “e.preventDefault()”.

At this point, we have a working anchor link – we could walk away and call it a day. But with just one more line of code we can animate its default behavior by using the animate method. The scrollTop property handles most of the work for us. The second argument you see “500” is a value in milliseconds, so adjust this accordingly.

Can’t see myself ever leaving an anchor link without applying some animation to it – it’s a cheap price to pay for something quite valuable.