Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to window.scrollTo() with a smooth effect [closed]

I can scroll to 200px using the following

btn.addEventListener("click", function(){     window.scrollTo(0,200); }) 

But I want a smooth scroll effect. How do I do this?

like image 634
KolaCaine Avatar asked Feb 15 '17 22:02

KolaCaine


People also ask

How do you link a smooth scroll anchor?

You can use window. scroll() with behavior: smooth and top set to the anchor tag's offset top which ensures that the anchor tag will be at the top of the viewport.

How does window scrollTo work?

Parameters: The scrollTo() method accepts two parameters as described below: x-coord: It is the pixel along the horizontal axis of the document that is displayed in the upper left. It is the required field. y-coord: It is the pixel along the vertical axis of the document that is displayed in the upper left.

How do you navigate to another page with a smooth scroll on a specific ID?

Modern Browsers detect the hash in the url and then automatically open that part. So, if you want to scroll smoothly to that part instead, you first need to reset the scroll position to 0 and then add smooth scrolling. // direct browser to top right away if (window. location.


2 Answers

2018 Update

Now you can use just window.scrollTo({ top: 0, behavior: 'smooth' }) to get the page scrolled with a smooth effect.

const btn = document.getElementById('elem');    btn.addEventListener('click', () => window.scrollTo({    top: 400,    behavior: 'smooth',  }));
#x {    height: 1000px;    background: lightblue;  }
<div id='x'>    <button id='elem'>Click to scroll</button>  </div>

Older solutions

You can do something like this:

var btn = document.getElementById('x');    btn.addEventListener("click", function() {    var i = 10;    var int = setInterval(function() {      window.scrollTo(0, i);      i += 10;      if (i >= 200) clearInterval(int);    }, 20);  })
body {    background: #3a2613;    height: 600px;  }
<button id='x'>click</button>

ES6 recursive approach:

const btn = document.getElementById('elem');    const smoothScroll = (h) => {    let i = h || 0;    if (i < 200) {      setTimeout(() => {        window.scrollTo(0, i);        smoothScroll(i + 10);      }, 10);    }  }    btn.addEventListener('click', () => smoothScroll());
body {    background: #9a6432;    height: 600px;  }
<button id='elem'>click</button>
like image 178
kind user Avatar answered Sep 20 '22 09:09

kind user


$('html, body').animate({scrollTop:1200},'50'); 

You can do this!

like image 41
Myco Claro Avatar answered Sep 19 '22 09:09

Myco Claro