Jquery Scroll to anchor tag on page


/ Published in: jQuery
Save to your folder(s)

You will want to include the jquery easing plugin: http://gsgd.co.uk/sandbox/jquery/easing/

Add a class of 'scroll' to any element that should slide to an anchor tag. You must give the anchor tag an id equal to the name.


Copy this code and paste it in your HTML
  1. $(document).ready(function(){
  2. $(".scroll").click(function(event){
  3. //prevent the default action for the click event
  4. event.preventDefault();
  5.  
  6. //get the full url - like mysitecom/index.htm#home
  7. var full_url = this.href;
  8.  
  9. //split the url by # and get the anchor target name - home in mysitecom/index.htm#home
  10. var parts = full_url.split("#");
  11. var trgt = parts[1];
  12.  
  13. //get the top offset of the target anchor
  14. var target_offset = $("#"+trgt).offset();
  15. var target_top = target_offset.top;
  16.  
  17. //goto that anchor by setting the body scroll top to anchor top
  18. $('html, body').animate({scrollTop:target_top}, 2000, 'easeOutQuad');
  19. });
  20. });

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.