detect the total added up scroll distance - javascript

I want to detect the total distance the user scrolled on a website. Therefore I want to add up the scroll distance downwards as well as the scroll distance upwards.
So for example: the user scrolls 150px downwards and scroll back to the top of the page the result should be 300px.
With window.pageYOffset I can detect the distance downwards. How can I add both directions up?
// edit:

You need a counter – totalOffset. You need to check current scroll position – currOffset. You need a function that fires on scroll and calculates the distance between current and cached position and that updates the counter and the cached position.
let totalOffset = 0;
let currOffset = window.pageYOffset;
window.addEventListener(
"scroll",
() => {
let addedOffset = Math.abs(currOffset - window.pageYOffset);
totalOffset += addedOffset;
currOffset = window.pageYOffset;
console.log('the total scroll in px is: ', totalOffset);
},
false
);
<div style="min-height:2000px">
<div>
It might not work ideally in SO snippet runner, but it seems to work fine in a browser.

Related

Reduce logo size for sticky header based on scroll position

This question has been asked here many times but I am looking to do this differently using Vanilla Javascript and not jQuery.
I need to reduce the logo size based on the scroll position but not suddenly. Adding a class to reduce the logo size is understood but I am looking to have the logo grow/shrink based on the exact scroll position.
The logo needs to stop at 200px wide down from 300px wide on scroll down.
When the user scrolls back up to a certain point the logo begins to increase back to 300px but still based on scroll position and not instantly based on a point.
Something similar to this on Codepen:
https://codepen.io/jonathanphz/pen/NAXRKG
var expandDiv = document.getElementById("expand");
var speed = 5;
function expanding() {
var scrolltop = window.pageYOffset; // get number of pixels document has scrolled vertically
var scrollAndSpeed = (scrolltop / speed);
//Expand using transform
//expandDiv.style.transform = "scalex( " + Math.min(Math.max(scrollAndSpeed, 1), 10) + ")";
//Or using width
expandDiv.style.width = Math.min(Math.max(scrollAndSpeed, 20), 95) + "%";
}
window.addEventListener('scroll', function() { // on page scroll
requestAnimationFrame(expanding); // call parallaxing()
}, false);```
You can use window.onscroll in vanilla JavaScript.
add condition with document.body.scrollTop and compare it, then change the styling(width and height) accordingly.
It will help you.

Vertically scroll content within viewport with timer

Is there a process to get a website that has a height that overflows the viewport to scroll at certain intervals to the first item that isn't in the view port, and so on for the next page until the bottom is reached and the page is reloaded starting at the top repeating the process.
Example would be a schedule of events that contained scores and users are viewing them at the venue.
You could use requestAnimationFrame to set up an animation loop, then scroll the page with javascript, until the end of the page is reached, and restart.
!function scroll() {
var current = document.body.scrollHeight - document.documentElement.clientHeight
if (current == document.body.scrollTop)
document.body.scrollTop = -1
document.body.scrollTop += 1
requestAnimationFrame(scroll)
}()
JSFiddle example

if distance between two elements is less than X do Y

I'm trying to calculate the distance between a website footer and a sidebar (which has a variable margin-top property as it's mimicking a fixed position element.)
In smaller resolutions, the sidebar will scroll on top of the footer. To solve this, I want to hide the sidebar when it's X px from the footer and then show it again once it's scrolled X px above the footer.
I've tried the below code (which is inside a window scroll function) but this is returning a negative number & isn't working as expected.
distance = sidebar.offset().top - footer.offset().top;
console.log(distance);
if ( distance > -500) {
sidebar.fadeOut('fast');
} else {
sidebar.fadeIn('fast');
}
Try this.
$(window).scroll(function() {
//changed order, now you won't get negative number
distance = (footer.offset().top - footer.outerHeight() ) - sidebar.offset().top;
if( distance <= 50 ) // 50 or any distance you want
sidebar.fadeOut(500);
else
sidebar.fadeIn(500);
});
Added that part inside $(window).scroll() so that it'll be checked every time you scroll.

How to properly scroll an overflowing div based on mouse position within its container

I am working on a small jQuery plugin that autoscrolls through a set of overflowing elements within a container div based on the mouse position within that container div.
See the Demo Here
The idea is for this plugin to be an improvement of something I wrote a while ago. See the autoscrolling navigation in the lower left here The old problem with this was that it jumps around when you mouseenter from anywhere but the bottom(javascript perspective) of the container div.
Now everything is working fine with my plugin but when you mouseenter from the top it screws up from time to time(move your mouse in and out fast and it will happen for sure), I think this is because I am getting different values from my mouseenter event and my mousemove event which are both used to calculate how to scroll the inner elements. Here is the function, the rest of the source is pretty small and decently commented.
projList.mousemove(function(e){
//keep it from freaking out when we mouseenter from Top of div
if(enterMouseY > divHeight){
enterMouseY = divHeight;
}
mouseY = e.pageY-projList.offset().top;
//ok that didnt work... try to keep it from freaking out when we mouseenter from Top of div
if (mouseY > divHeight){
mouseY = divHeight;
}
//distnace from top of container div to where our mouse Entered
var distToTop = divHeight - enterMouseY;
//here is the calculation, I parameterize the mouseY pos as a value between 0-1
//0 being where we entered and 1 being the top or bottom of the div
//then multiply that by how much we have to scroll to get to the end of the list
//are we moving up or down
if(mouseY>enterMouseY){
//if up calculate based on Top
var dist =totalScrollDistance * ((mouseY-enterMouseY-projList.offset().top)/(distToTop));
}else if(mouseY<enterMouseY){
//if up calculate based on Bottom
var dist =totalScrollDistance * ((mouseY-enterMouseY-projList.offset().top)/(enterMouseY));
}else if(mouseY = enterMouseY){
var dist = 0;
}
//set the position of the list offsetting wherever we left it
pos = dist+lastPos;
//scroll to that position
projList.scrollTop(pos);
//are we trying to scroll past the scrollable amount
if(pos<0){
pos = 0;
}
if(pos>totalScrollDistance){
pos = totalScrollDistance;
}
$('#div1').text("mouseY: "+ mouseY +" enterMouseY: "+ enterMouseY +" distance:"+ dist.toFixed(1) + " pos:"+ pos.toFixed(1));
});
I solved this problem, there was an error in my calculations, but works how I described above.
You can see it in action here
http://web.archive.org/web/20130529212243/http://www.robincwillis.com/AutoScroll/

How to change scrollbar position?

Is it possible to change the scrollbar position when the user reaches a certain point scrolling down a web page? For example once you reached half way down down the page the scrollbar would move automatically back to the top.
You can calculate the percentage of the current position of the scrollbar using the onscroll event, and if it reaches the 50 % the scroll position can be set to the top of the page with the scrollTo function:
window.onload = function () {
window.onscroll = function () {
var doc = document.body,
scrollPosition = doc.scrollTop,
pageSize = (doc.scrollHeight - doc.clientHeight),
percentageScrolled = Math.floor((scrollPosition / pageSize) * 100);
if (percentageScrolled >= 50){ // if the percentage is >= 50, scroll to top
window.scrollTo(0,0);
}
};
};
You can check my example here.
Yup, I've seen it a few times. Here is some JS code:
window.scrollBy(0,50)
50 is the amount of pixels you want to scroll by.
The three scrolling functions you'll want to concern yourself with are window.scroll(x,y), window.scrollBy(dx,dy), and window.scrollTo(x,y).
As David mentioned you'll need the scroll position to know where you are and use the window.onscroll event to fire off this calculation.
(window.pageYOffset || document.body.scrollTop || document.documentElement.scrollTop) ought to give you the current scroll position in just about any browser.

Categories