How to window.scrollTo() with a smooth effect
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>
How to make smooth scroll effect but with scrolling stop at a specified height?
Use window.scrollTo() instead of
element.scrollIntoView()
The scrollTo method is Polymorphic. Apart from the params you already know, it instead also takes just an object (dictionary) in which you can specify the scroll behavior, like so:
<script>
function scrollToJustAbove(element, margin=20) {
let dims = element.getBoundingClientRect();
window.scrollTo({
top: dims.top - margin,
behavior: 'smooth'
});
}
setTimeout(() => {
const classElement = document.getElementsByClassName("myclass");
if(classElement.length > 0){
scrollToJustAbove(classElement[0]);
}
}, 100);
</script>
Working Example: https://plnkr.co/edit/UevhAN4NmTCdw65dzuPe?p=preview
JavaScript - window.scroll({ behavior: 'smooth' }) not working in Safari
Behavior options aren't fully supported in IE/Edge/Safari, so you'd have to implement something on your own. I believe jQuery has something already, but if you're not using jQuery, here's a pure JavaScript implementation:
function SmoothVerticalScrolling(e, time, where) {
var eTop = e.getBoundingClientRect().top;
var eAmt = eTop / 100;
var curTime = 0;
while (curTime <= time) {
window.setTimeout(SVS_B, curTime, eAmt, where);
curTime += time / 100;
}
}
function SVS_B(eAmt, where) {
if(where == "center" || where == "")
window.scrollBy(0, eAmt / 2);
if (where == "top")
window.scrollBy(0, eAmt);
}
And if you need horizontal scrolling:
function SmoothHorizontalScrolling(e, time, amount, start) {
var eAmt = amount / 100;
var curTime = 0;
var scrollCounter = 0;
while (curTime <= time) {
window.setTimeout(SHS_B, curTime, e, scrollCounter, eAmt, start);
curTime += time / 100;
scrollCounter++;
}
}
function SHS_B(e, sc, eAmt, start) {
e.scrollLeft = (eAmt * sc) + start;
}
And an example call is:
SmoothVerticalScrolling(myelement, 275, "center");
Scroll smoothly to specific element on page
Just made this javascript only solution below.
Simple usage:
EPPZScrollTo.scrollVerticalToElementById('signup_form', 20);
Engine object (you can fiddle with filter, fps values):
/**
*
* Created by Borbás Geri on 12/17/13
* Copyright (c) 2013 eppz! development, LLC.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
* The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*
*/
var EPPZScrollTo =
{
/**
* Helpers.
*/
documentVerticalScrollPosition: function()
{
if (self.pageYOffset) return self.pageYOffset; // Firefox, Chrome, Opera, Safari.
if (document.documentElement && document.documentElement.scrollTop) return document.documentElement.scrollTop; // Internet Explorer 6 (standards mode).
if (document.body.scrollTop) return document.body.scrollTop; // Internet Explorer 6, 7 and 8.
return 0; // None of the above.
},
viewportHeight: function()
{ return (document.compatMode === "CSS1Compat") ? document.documentElement.clientHeight : document.body.clientHeight; },
documentHeight: function()
{ return (document.height !== undefined) ? document.height : document.body.offsetHeight; },
documentMaximumScrollPosition: function()
{ return this.documentHeight() - this.viewportHeight(); },
elementVerticalClientPositionById: function(id)
{
var element = document.getElementById(id);
var rectangle = element.getBoundingClientRect();
return rectangle.top;
},
/**
* Animation tick.
*/
scrollVerticalTickToPosition: function(currentPosition, targetPosition)
{
var filter = 0.2;
var fps = 60;
var difference = parseFloat(targetPosition) - parseFloat(currentPosition);
// Snap, then stop if arrived.
var arrived = (Math.abs(difference) <= 0.5);
if (arrived)
{
// Apply target.
scrollTo(0.0, targetPosition);
return;
}
// Filtered position.
currentPosition = (parseFloat(currentPosition) * (1.0 - filter)) + (parseFloat(targetPosition) * filter);
// Apply target.
scrollTo(0.0, Math.round(currentPosition));
// Schedule next tick.
setTimeout("EPPZScrollTo.scrollVerticalTickToPosition("+currentPosition+", "+targetPosition+")", (1000 / fps));
},
/**
* For public use.
*
* @param id The id of the element to scroll to.
* @param padding Top padding to apply above element.
*/
scrollVerticalToElementById: function(id, padding)
{
var element = document.getElementById(id);
if (element == null)
{
console.warn('Cannot find element with id \''+id+'\'.');
return;
}
var targetPosition = this.documentVerticalScrollPosition() + this.elementVerticalClientPositionById(id) - padding;
var currentPosition = this.documentVerticalScrollPosition();
// Clamp.
var maximumScrollPosition = this.documentMaximumScrollPosition();
if (targetPosition > maximumScrollPosition) targetPosition = maximumScrollPosition;
// Start animation.
this.scrollVerticalTickToPosition(currentPosition, targetPosition);
}
};
Scroll to the top of the page using JavaScript?
If you don't need the change to animate then you don't need to use any special plugins - I'd just use the native JavaScript window.scrollTo()
method -- passing in 0, 0
will scroll the page to the top left instantly.
window.scrollTo(xCoord, yCoord);
Parameters
- xCoord is the pixel along the horizontal axis.
- yCoord is the pixel along the vertical axis.
window.scroll smooth not working on Safari
window.scroll
is supported, but scroll-behavior
CSS is not.
https://developer.mozilla.org/en-US/docs/Web/CSS/scroll-behavior
Pending support, consider using the smoothscroll-polyfill which adds smooth scrolling support for Safari, IE, and Edge.
JS for smooth scroll to the bottom of the page
There is no such thing as scrollToBottom
. Try this:
$("html, body").animate({ scrollTop: document.body.scrollHeight }, "slow");
Related Topics
Calculate Color Values from Green to Red
Jquery to Change Style Attribute of a Div Class
Jquery Mobile Prevent Scroll-To-Top Before Page Transition
Why Can't JavaScript .Play() Audio Files on iPhone Safari
Converting Milliseconds to a Date (Jquery/Javascript)
Document.Getelementbyid VS Jquery $()
Mismatched Anonymous Define() Module
Google Map API Uncaught Typeerror: Cannot Read Property 'Offsetwidth' of Null
Is It True That Every Function in JavaScript Is a Closure
How to Select All Text in Contenteditable Div
Jquery/JavaScript Opacity Animation with Scroll
Converting Em to Px in JavaScript (And Getting Default Font Size)
How to Use Materialize-CSS with Angular
How to Open an External Link in Safari Not the App's Uiwebview
Why Is Arr = [] Faster Than Arr = New Array
How to Convert a Float Number to a Whole Number in JavaScript