I was looking for a way to change a div position based on scroll direction using Javascript only.
I found a great resource from lehollandaisvolant on CodePen which got me on the right track. (Big thank you!) This code outputs html content that displays the direction which the user is scrolling.
Here is the original code:
HTML
<p>Because i’m sick of using tons of shit for this basic function.</p>
<p>This uses no timing functions, no jQuery and fits everywhere.</p>
<pre>
Scroll me.
Scroll me.
Scroll me.
Scroll me.
Scroll me.
Scroll me.
</pre>
<div id="info-box" data-scroll-direction="no scrolling yet, go on!">
Your last scolling direction was:
</div>
CSS
#info-box {
padding: 50px;
position: fixed;
background: #fafafa;
box-shadow: 3px 3px 3px silver;
top: 20px;
right: 20px;
}
#info-box::after {
content: attr(data-scroll-direction);
}
pre {
line-height: 250px;
}
JAVASCRIPT
var scrollPos = 0; // Initial state
window.addEventListener('scroll', function(){ // adding scroll event
// detects new state and compares it with the new one
if ((document.body.getBoundingClientRect()).top > scrollPos)
document.getElementById('info-box').setAttribute('data-scroll-direction', 'UP');
else
document.getElementById('info-box').setAttribute('data-scroll-direction', 'DOWN');
// saves the new position for iteration.
scrollPos = (document.body.getBoundingClientRect()).top;
});```
In order to change the div position however, I simply changed the If/Else statement to fit my desired css criteria:
// Initial state
var scrollPos = 0;
// adding scroll event
window.addEventListener('scroll', function(){
// detects new state and compares it with the new one
if ((document.body.getBoundingClientRect()).top > scrollPos)
document.getElementById('info-box').style.margin = '100px 0 0 0';
else
document.getElementById('info-box').style.margin = '0px 0 0 0';
scrollPos = (document.body.getBoundingClientRect()).top;
});
Specifically:
if ((document.body.getBoundingClientRect()).top > scrollPos)
document.getElementById('info-box').style.margin = '100px 0 0 0';
else
document.getElementById('info-box').style.margin = '0px 0 0 0';
Hopefully someone may find this useful in trying to change a div's css position based on scroll direction, or trying to do something similar.
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.