ScrollTo Anchor tags using jQuery

A quick jQuery plugin to over-ride/replace the jump-to action with a smooth-easing scroll action for anchored links. This will be updated with an option to set the duration

jQuery Plugin

(function($){
  $.fn.weighAnchor = function() {
    this.each(function(){	
    $(this).click(function(){
      var scrollTo = $(this).attr("href");
      $('html, body, #container').animate({scrollTop: $(scrollTo).offset().top}, 2000);
      return false;
    });
  });
 };
})(jQuery);

Javascript

$(document).ready(function(){
  $('.weigh-anchor').weighAnchor();
});

HTML

<a id="container">
  <a class="weigh-anchor" href="#anchors-aweigh">Scroll to Element ID</a>
  <h3 id="anchors-aweigh">Anchors Aweigh</h3>
</div>

It is usually good practice to have a div element wrapping your content, and in this case it is needed for browsers like chrome and safari to make this plugin work properly. They will not animate from html, body like mozilla or ie, but will animate from body, #container.

This entry was posted in Web Development and tagged , , , , . Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *