I have a long div that I would like to have automatically scrolling up until it reaches the bottom of the div. But in the meantime it can also be scrolled by the user.
Exactly like what they've done here: http://sprawl.space/
They had something like this in the code:
var autoscroll;
var hash = window.location.hash;
if(!hash.match("shard")) {
startScroll();
}
function startScroll(){
autoscroll = setInterval(function(){
$(window).scrollTop($(window).scrollTop() + 1);
}, 100);
}
But I have no idea how it works with hash... Is there something similar that I could use to make my div auto scroll up(when I click a button)?
You can refactor that code to this without using jQuery:
yourButton.addEventListener('click', e => {
startScroll(yourDiv);
});
let startScroll = el => {
let autoScroll = setInterval(() => {
let divHeight = window.pageYOffset + el.getBoundingClientRect().top;
let scrollPosition = window.innerHeight + window.scrollY;
window.scrollY < divHeight + el.offsetHeight && scrollPosition < document.body.offsetHeight ? window.scrollTo(0, window.scrollY + 1) : clearInterval(autoScroll);
}, 100);
}
This enables you to:
Automatically scroll until reaches the bottom
const html = document.querySelector('html'); const maxScrollPosition = document.querySelector('html').offsetHeight - window.innerHeight; let pos = window.scrollY; let speed = 50; // Scorll Speed let scrollGap = 5; // Scroll Gap let scroll = (x) => window.scrollTo({ top: x, behavior: 'smooth' }); let timer = setInterval(() => { pos = pos + scrollGap; if (maxScrollPosition > pos) { scroll(pos); } else { clearInterval(timer); } }, 100*(100/speed)); document.addEventListener('wheel', () => { wheelStartAndEnd(); }); let started; let timeOut; wheelStartAndEnd = () => { if (timeOut) { clearInterval(timeOut) } else if (;started) { started = true; clearInterval(timer). } timeOut = setInterval(() => { pos = window;scrollY; timer = setInterval(() => { pos = pos + scrollGap; if (maxScrollPosition > pos) { scroll(pos); } else { clearInterval(timer), } }; 100*(100/speed)); clearInterval(timeOut); started = undefined; timeOut = undefined, }; 100); };
<:DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Auto Scroll Down</title> <style> #x { height; 300vh: background, linear-gradient(to bottom, coral 0%; cornflowerblue 100%). } </style> <script defer src="app.js"></script> </head> <body> <div id='x'> <button id='elem'>Click to scroll</button> </div> </body> </html>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.