I have the following simple scrollTop()
function obtained from w3schools. The issue i have is setting the time for scrolling. Different people gave different methods and everyone removed one or all lines from the following code. I'm waiting for a function which can be added to set the scrolling speed and no other text is to be removed. Here's the codepen work
var mybutton = document.getElementById("myBtn");
window.onscroll = function() {
scrollFunction()
};
function scrollFunction() {
if (document.body.scrollTop > 20 || document.documentElement.scrollTop > 20) {
mybutton.style.display = "block";
} else {
mybutton.style.display = "none";
}
}
// When the user clicks on the button, scroll to the top of the document
function topFunction() {
document.body.scrollTop = 0;
document.documentElement.scrollTop = 0;
}
body {
font-family: Arial, Helvetica, sans-serif;
font-size: 20px;
}
#myBtn {
display: none;
position: fixed;
bottom: 20px;
right: 30px;
z-index: 99;
font-size: 18px;
border: none;
outline: none;
background-color: red;
color: white;
cursor: pointer;
padding: 15px;
border-radius: 4px;
}
#myBtn:hover {
background-color: #555;
}
html {
scroll-behavior: smooth
}
<button onclick="topFunction()" id="myBtn" title="Go to top">Top</button>
<div style="background-color:black;color:white;padding:30px">Scroll Down</div>
<div style="background-color:lightgrey;padding:30px 30px 2500px">This example demonstrates how to create a "scroll to top" button that bees visible
<strong>when the user starts to scroll the page</strong></div>
I have the following simple scrollTop()
function obtained from w3schools. The issue i have is setting the time for scrolling. Different people gave different methods and everyone removed one or all lines from the following code. I'm waiting for a function which can be added to set the scrolling speed and no other text is to be removed. Here's the codepen work https://codepen.io/vkdatta27/pen/zYqQbmM
var mybutton = document.getElementById("myBtn");
window.onscroll = function() {
scrollFunction()
};
function scrollFunction() {
if (document.body.scrollTop > 20 || document.documentElement.scrollTop > 20) {
mybutton.style.display = "block";
} else {
mybutton.style.display = "none";
}
}
// When the user clicks on the button, scroll to the top of the document
function topFunction() {
document.body.scrollTop = 0;
document.documentElement.scrollTop = 0;
}
body {
font-family: Arial, Helvetica, sans-serif;
font-size: 20px;
}
#myBtn {
display: none;
position: fixed;
bottom: 20px;
right: 30px;
z-index: 99;
font-size: 18px;
border: none;
outline: none;
background-color: red;
color: white;
cursor: pointer;
padding: 15px;
border-radius: 4px;
}
#myBtn:hover {
background-color: #555;
}
html {
scroll-behavior: smooth
}
<button onclick="topFunction()" id="myBtn" title="Go to top">Top</button>
<div style="background-color:black;color:white;padding:30px">Scroll Down</div>
<div style="background-color:lightgrey;padding:30px 30px 2500px">This example demonstrates how to create a "scroll to top" button that bees visible
<strong>when the user starts to scroll the page</strong></div>
Share
Improve this question
asked Oct 3, 2020 at 4:25
Maniac PianoManiac Piano
1471 gold badge3 silver badges12 bronze badges
6
- Read this stackoverflow./questions/33686523/… – LahiruTM Commented Oct 3, 2020 at 4:27
- Check out the scrollTo function, setting behavior: 'smooth', you'll need to confirm your required browser patibility: developer.mozilla/en-US/docs/Web/API/Element/scrollTo – Emilio Commented Oct 3, 2020 at 4:30
- @LahiruTM, I've seen that. But i have already mentioned that i want to make only additions in following code. Cam you make amy additions in following code? – Maniac Piano Commented Oct 3, 2020 at 4:32
-
@emiliokyp,
scroll behavior: smooth
is already added in the css. I want to control it's time. See, example, the scroll top function needs to happen in 8 seconds – Maniac Piano Commented Oct 3, 2020 at 4:35 - 1 Load Jquery in script section. then ment two lines in top function and put this. $('html,body').animate({ scrollTop: 0 }, 'slow'); – LahiruTM Commented Oct 3, 2020 at 4:43
5 Answers
Reset to default 5Here is a pure Javascript solution. you may need to remove scroll-behavior: smooth
style as this interrupts slow scrolling. in javascript scrollTo
function provide the second parameters in milliseconds
and function will take that much time to scroll to top.
JS code referred from the answer @ https://stackoverflow./a/23844067
var mybutton = document.getElementById("myBtn");
window.onscroll = function() {
scrollFunction()
};
function scrollFunction() {
if (document.body.scrollTop > 20 || document.documentElement.scrollTop > 20) {
mybutton.style.display = "block";
} else {
mybutton.style.display = "none";
}
}
// Bind your button click, scroll direction and effect speed
document.getElementById("myBtn").onclick = function() {
scrollTo(0, 8000); // it will take 8 seconds to reach to top.
}
// Element to move, time in ms to animate
function scrollTo(element, duration) {
var e = document.documentElement;
if (e.scrollTop === 0) {
var t = e.scrollTop;
++e.scrollTop;
e = t + 1 === e.scrollTop-- ? e : document.body;
}
scrollToC(e, e.scrollTop, element, duration);
}
// Element to move, element or px from, element or px to, time in ms to animate
function scrollToC(element, from, to, duration) {
if (duration <= 0) return;
if (typeof from === "object") from = from.offsetTop;
if (typeof to === "object") to = to.offsetTop;
scrollToX(element, from, to, 0, 1 / duration, 20, easeOutCuaic);
}
function scrollToX(element, xFrom, xTo, t01, speed, step, motion) {
if (t01 < 0 || t01 > 1 || speed <= 0) {
element.scrollTop = xTo;
return;
}
element.scrollTop = xFrom - (xFrom - xTo) * motion(t01);
t01 += speed * step;
debugger;
setTimeout(function() {
scrollToX(element, xFrom, xTo, t01, speed, step, motion);
}, step);
}
function easeOutCuaic(t) {
t--;
return t * t * t + 1;
}
body {
font-family: Arial, Helvetica, sans-serif;
font-size: 20px;
}
#myBtn {
display: none;
position: fixed;
bottom: 20px;
right: 30px;
z-index: 99;
font-size: 18px;
border: none;
outline: none;
background-color: red;
color: white;
cursor: pointer;
padding: 15px;
border-radius: 4px;
}
#myBtn:hover {
background-color: #555;
}
<button onclick="topFunction()" id="myBtn" title="Go to top">Top</button>
<div style="background-color:black;color:white;padding:30px">Scroll Down</div>
<div style="background-color:lightgrey;padding:30px 30px 2500px">This example demonstrates how to create a "scroll to top" button that bees visible
<strong>when the user starts to scroll the page</strong></div>
Here is the solution to slow down the scroll speed by using javascript
This work for me
// Set the scroll speed factor
let scrollSpeed = 0.5;
// Add an event listener for the 'wheel' event
document.addEventListener('wheel', function(event) {
// Prevent default scrolling behavior
event.preventDefault();
// Calculate the new scroll position
let delta = event.deltaY;
let scrollPosition = window.scrollY + (delta * scrollSpeed);
// Set the new scroll position
window.scrollTo({
top: scrollPosition,
behavior: 'smooth'
});
}, { passive: false });
You can simply add the smooth scroll using
html {
scroll-behavior: smooth;
}
Note that it's not supported by Safari yet :/ (check here)
Also there is Smooth Scroll GitHub repo by Ferdinandi I think it helps, just take a look at it and it's features.
This method works for all anchors. For other values you can simplify it by spacing it from the top of the page.
document.addEventListener("DOMContentLoaded", function() {
document.querySelectorAll("a").forEach(function(anchor) {
anchor.addEventListener("click", function(event) {
if (this.hash !== "" && this.hash.startsWith("#")) {
event.preventDefault();
const target = document.querySelector(this.hash);
if (target) {
smoothScrollTo(window.scrollY, target.offsetTop, 1000); // (800ms)
history.pushState(null, null, this.hash);
}
}
});
});
function smoothScrollTo(start, end, duration) {
let startTime = null;
function animationStep(currentTime) {
if (!startTime) startTime = currentTime;
let timeElapsed = currentTime - startTime;
let progress = Math.min(timeElapsed / duration, 1);
let easeInOut = progress < 0.5
? 2 * progress * progress
: 1 - Math.pow(-2 * progress + 2, 2) / 2;
window.scrollTo(0, start + (end - start) * easeInOut);
if (timeElapsed < duration) {
requestAnimationFrame(animationStep);
}
}
requestAnimationFrame(animationStep);
}
});
#section1 {
height: 1000px;
background-color: pink;
}
#section2 {
height: 1000px;
background-color: yellow;
}
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<h1>Smooth Scroll</h1>
<div class="main" id="section1">
<h2>Section 1</h2>
<p>Click on the link to see the "smooth" scrolling effect.</p>
<a href="#section2">Click Me to Smooth Scroll to Section 2 Below</a>
<p>Note: Remove the scroll-behavior property to remove smooth scrolling.</p>
</div>
<div class="main" id="section2">
<h2>Section 2</h2>
<a href="#section1">Click Me to Smooth Scroll to Section 1 Above</a>
</div>
</body>
</html>
animated-scroll-to it works find.
https://www.npmjs./package/animated-scroll-to
animateScrollTo(el as Element, {
elementToScroll: elContainer,
speed: 100,
}).then();