I\'m designing a very simple web page (HTML only), the only \"feature\" I want to implement is to do something when the user scrolls down the page, is there a way to capture
Here is my solution in pure JavaScript, be careful the only problem is that it is executed a lot of times. Sorry for the spelling I use google translate, I am french ;)
var scrollBefore = 0;
window.addEventListener('scroll',function(e){
const scrolled = window.scrollY;
if(scrollBefore > scrolled){
console.log("ScrollUP");
scrollBefore = scrolled;
//Desired action
}else{
scrollBefore = scrolled;
console.log("ScrollDOWN");
//Desired action
}
})
If you don't want to use jQuery (which you might not do for a very simple HTML page), you can accomplish this using regular Javascript:
<script>
function scrollFunction() {
// do your stuff here;
}
window.onscroll = scrollFunction;
</script>
You mentioned that you wanted to do something when they scroll down the page - the onscroll event fires off scrolling in any direction, in either the x- or y-axis, so your function will be called any time they scroll.
If you really want it to only run your code when they scrolled down the page, you'd need to preserve the previous scroll position to compare against whenever onscroll gets called.
/**
* This function will determine if a client mousewheel is scrolling up or down.
*/
//window.addEventListener("load", eScroll);
function eScroll() {
window.addEventListener('mousewheel', (event)=> {
let originalEvent = event.wheelDeltaY;
if (event.wheelDeltaY >= 0) {
console.log('Scroll up');
}
else {
console.log('Scroll down');
}
});
}
window.addEventListener("load", scrollDown);
function scrollDown() {
window.addEventListener('mousewheel', (event)=> {
if (event.wheelDeltaY <= 0) {
console.log(event.wheelDeltaY);
console.log('Mousewheel has scrolled down');
}
})
}
window.addEventListener("load", scrollUp);
function scrollUp() {
window.addEventListener('mousewheel', (event)=> {
if (event.wheelDeltaY > 0) {
console.log(event.wheelDeltaY);
console.log('Mousewheel has scrolled up');
}
})
}
Check if the user scrolled up and simply return
window.addEventListener(
"scroll",
e => {
const scrolled = window.scrollY; // Number of pixels the user has scrolled
let lastScrolled = 0; // Number of pixels the user has scrolled in the last event
// If the user scrolls down, the scrolled value goes up and vice versa
// So basically
if (scrolled < lastScrolled) {
// Then the user scrolled up!
console.log("GET OUT! YOU SCROLLED UP!");
// But you should update the lastScrolled value nonetheless
lastScrolled = scrolled;
return; // And then get out!
}
lastScrolled = scrolled; // The value gets updated in any case
// And your code goes here
},
false
);