user1691389
user1691389

Reputation: 453

javascript smooth scroll on click

I'm using this link:

<a class="" onclick="location.href='#top'" href="superContent">superContent</a>

It does two things at once:

  1. Jumps user to top of the page
  2. Performs this other (unrelated) ajax load function

Everything works great, except I'm trying to figure out how to get it to scroll to the top more smoothly. I've tried adding .scroll to attach it to my jquery scrollTo plugin, but nothing happens, which probably has something to do with the fact that I'm using javascript onclick, while the href attribute does something else entirely.

Is there a way to attach animated smooth-scrolling to onclick="location.href='#top'" ?

Upvotes: 16

Views: 73678

Answers (2)

vsync
vsync

Reputation: 130065

document.querySelector('button').addEventListener('click', function(){
   scrollTo( document.querySelector('aside'), Math.floor(Math.random() * 1000) + 1  , 600 );   
});
    
function scrollTo(element, to, duration) {
    var start = element.scrollTop,
        change = to - start,
        currentTime = 0,
        increment = 20;
        
    var animateScroll = function(){        
        currentTime += increment;
        var val = Math.easeInOutQuad(currentTime, start, change, duration);
        element.scrollTop = val;
        if(currentTime < duration) {
            setTimeout(animateScroll, increment);
        }
    };
    animateScroll();
}

//t = current time
//b = start value
//c = change in value
//d = duration
Math.easeInOutQuad = function (t, b, c, d) {
  t /= d/2;
  if (t < 1) return c/2*t*t + b;
  t--;
  return -c/2 * (t*(t-2) - 1) + b;
};
button{ float:left; }
aside{ height:200px; width:50%; border:2px dashed red; overflow:auto; }
aside::before{
  content:''; 
  display:block; 
  height:1000px;  
  background: linear-gradient(#3f87a6, #ebf8e1, #f69d3c);
}
<button>click to random scroll</button>
<aside></aside>

Upvotes: 5

Try this, it animates the scrollTop() function.

Set link's id:

<a id="link">link</a>

jquery to scroll:

$('#link').click(function(e){
  var $target = $('html,body');
  $target.animate({scrollTop: $target.height()}, 500);
});

Upvotes: 40

Related Questions