authorandrew
authorandrew

Reputation: 185

Javascript-only smooth scroll on button press

This site has a full-height image to start. Further content is located below the fold, with a 'scroll' element at the bottom of the image to prompt users to discover the rest of the content. On click, I've succeeded in making the site scroll down by 300 pixels. I want to do this smoothly, however. Here is my current code:

  window.onload = function () { 
    var scroll = document.getElementById("scroll");
    scroll.onclick = function () {
        var top = self.pageYOffset; 
        var goal = 300; 
        for(var i=0, l=goal; i<l; ++i) {
        window.scrollBy(0,1);
        }       
   }; 
};

This works for scrolling, but not smoothly. I thought that if I had the for loop, changing the window.scrollBy value to something like .001 would make it scroll more slowly (thus, smoothly), but that function doesn't seem to take decimal points.

Any tips? Technically it's fine now, but I'd rather add that last bit of polish. Thanks!

Upvotes: 0

Views: 294

Answers (2)

Alex Bobko
Alex Bobko

Reputation: 26

Your code runs very fast and you don't see a smooth effect. You must use the setInterval() function, and scroll to the 300/n px in each iteration (n - number of iterations). Like this:

window.onload = function () { 
    var scroll = document.getElementById("scroll");
    scroll.onclick = function () {
        var currentScroll = 0; 
        var goal = 300;
        var step = goal/10
        var timer = setInterval( function () {
            if (currentScroll < goal) {
                window.scrollBy(0, step);
                currentScroll += step;
            } else {
                clearInterval(timer);
            }
        }, 50);
    };
};       

Upvotes: 1

ѺȐeallү
ѺȐeallү

Reputation: 3017

Try something like this...example

 $(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;
          }
        }
      });
    });

Upvotes: 0

Related Questions