[javascript] jquery smooth scroll to an anchor?

Is there a way to scroll down to an anchor link using jQuery?

Like:

$(document).ready(function(){
  $("#gotomyanchor").click(function(){
      $.scrollSmoothTo($("#myanchor"));
  });
});

?

This question is related to javascript jquery

The answer is


I used the plugin Smooth Scroll, at http://plugins.jquery.com/smooth-scroll/. With this plugin all you need to include is a link to jQuery and to the plugin code:

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script type="text/javascript" src="javascript/smoothscroll.js"></script>

(the links need to have the class smoothScroll to work).

Another feature of Smooth Scroll is that the ancor name is not displayed in the URL!


Try this one. It is a code from CSS tricks that I modified, it is pretty straight forward and does both horizontal and vertial scrolling. Needs JQuery. Here is a demo

$(function() {
  $('a[href*=#]:not([href=#])').click(function() {
    if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'') && location.hostname == this.hostname) {
      var target = $(this.hash);
      target = target.length ? target : $('[name=' + this.hash.slice(1) +']');
      if (target.length) {
        $('html,body').animate({
          scrollTop: target.offset().top-10, scrollLeft:target.offset().left-10
        }, 1000);
        return false;
      }
    }
  });
});

Best solution I have seen so far: jQuery: Smooth Scrolling Internal Anchor Links

HTML:

<a href="#comments" class="scroll">Scroll to comments</a>

Script:

jQuery(document).ready(function($) {
    $(".scroll").click(function(event){     
        event.preventDefault();
        $('html,body').animate({scrollTop:$(this.hash).offset().top}, 500);
    });
});

I would use the simple code snippet from CSS-Tricks.com:

$(function() {
  $('a[href*=#]:not([href=#])').click(function() {
    if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'') && location.hostname == this.hostname) {
      var target = $(this.hash);
      target = target.length ? target : $('[name=' + this.hash.slice(1) +']');
      if (target.length) {
        $('html,body').animate({
          scrollTop: target.offset().top
        }, 1000);
        return false;
      }
    }
  });
});

Source: http://css-tricks.com/snippets/jquery/smooth-scrolling/


I hate adding function-named classes to my code, so I put this together instead. If I were to stop using smooth scrolling, I'd feel behooved to go through my code, and delete all the class="scroll" stuff. Using this technique, I can comment out 5 lines of JS, and the entire site updates. :)

<a href="/about">Smooth</a><!-- will never trigger the function -->
<a href="#contact">Smooth</a><!-- but he will -->
...
...
<div id="contact">...</div>


<script src="jquery.js" type="text/javascript"></script>
<script type="text/javascript">
    // Smooth scrolling to element IDs
    $('a[href^=#]:not([href=#])').on('click', function () {
        var element = $($(this).attr('href'));
        $('html,body').animate({ scrollTop: element.offset().top },'normal', 'swing');
        return false;
    });
</script>

Requirements:
1. <a> elements must have an href attribute that begin with # and be more than just #
2. An element on the page with a matching id attribute

What it does:
1. The function uses the href value to create the anchorID object
   - In the example, it's $('#contact'), /about starts with /
2. HTML, and BODY are animated to the top offset of anchorID
   - speed = 'normal' ('fast','slow', milliseconds, )
   - easing = 'swing' ('linear',etc ... google easing)
3. return false -- it prevents the browser from showing the hash in the URL
   - the script works without it, but it's not as "smooth".


works

$('a[href*=#]').each(function () {
    $(this).attr('href', $(this).attr('href').replace('#', '#_'));
    $(this).on( "click", function() {

        var hashname = $(this).attr('href').replace('#_', '');

        if($(this).attr('href') == "#_") {
            $('html, body').animate({ scrollTop: 0 }, 300);
        }
        else {
            var target = $('a[name="' + hashname + '"], #' + hashname),
                targetOffset = target.offset().top;
            if(targetOffset >= 1) {
                $('html, body').animate({ scrollTop: targetOffset-60 }, 300);
            }
        }
    });
});

jQuery.scrollTo will do everything you want and more!

You can pass it all kinds of different things:

  • A raw number
  • A string('44', '100px', '+=30px', etc )
  • A DOM element (logically, child of the scrollable element)
  • A selector, that will be relative to the scrollable element
  • The string 'max' to scroll to the end.
  • A string specifying a percentage to scroll to that part of the container (f.e: 50% goes to * to the middle).
  • A hash { top:x, left:y }, x and y can be any kind of number/string like above.

Here's the code I used to quickly bind jQuery scrollTo to all anchor links:

// Smooth scroll
$('a[href*=#]').click(function () {
    var hash = $(this).attr('href');
    hash = hash.slice(hash.indexOf('#') + 1);
    $.scrollTo(hash == 'top' ? 0 : 'a[name='+hash+']', 500);
    window.location.hash = '#' + hash;
    return false;
});

I wanted a version that worked for <a href="#my-id"> and <a href="/page#my-id">

<script>        
    $('a[href*=#]:not([href=#])').on('click', function (event) {
        event.preventDefault();
        var element = $(this.hash);
        $('html,body').animate({ scrollTop: element.offset().top },'normal', 'swing');
    });
</script>

I used in my site this:

$(document).ready(function(){
$('a[href^="#"]').on('click',function (e) {
    e.preventDefault();

    var target = this.hash,
    $target = $(target);

    $('html, body').stop().animate({
        'scrollTop': $target.offset().top
    }, 1200, 'swing', function () {
        window.location.hash = target;
    });
});

});

You could change the speed of the scrolling changing the "1200" i used by default, it works fairly well on most of the browsers.

after putting the code between the <head> </head> tag of your page, you will need to create the internal link in your <body> tag:

<a href="#home">Go to Home</a>

Hope it helps!

Ps: Dont forget to call:

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8/jquery.min.js"></script>


Using hanoo's script I created a jQuery function:

$.fn.scrollIntoView = function(duration, easing) {
    var dest = 0;
    if (this.offset().top > $(document).height() - $(window).height()) {
        dest = $(document).height() - $(window).height();
    } else {
        dest = this.offset().top;
    }
    $('html,body').animate({
        scrollTop: dest
    }, duration, easing);
    return this;
};

usage:

$('#myelement').scrollIntoView();

Defaults for duration and easing are 400ms and "swing".