How to determine scroll direction without actually scrolling - javascript

I am coding a page where the first time the user scrolls, it doesn't actually scroll the page down, instead it adds a class with a transition.
I'd like to detect when the user is scrolling down, because if he scrolls up, I want it to do something else.
All the methods that I've found are based on defining the current body ScrollTop, and then comparing with the body scrollTop after the page scrolls, defining the direction, but since the page doesn't actually scroll, the body scrollTop() doesn't change.
animationIsDone = false;
function preventScroll(e) {
e.preventDefault();
e.stopPropagation();
}
$('body').on('mousewheel', function(e) {
if (animationIsDone === false) {
$("#main-header").removeClass("yellow-overlay").addClass("yellow-overlay-darker");
$(".site-info").first().addClass("is-description-visible");
preventScroll(e);
setTimeout(function() {
animationIsDone = true;
}, 1000);
}
});
This is what I have come with, but that way it doesn't matter the direction I scroll it triggers the event

The mousewheel event is quickly becoming obsolete. You should use wheel event instead.
This would also easily allow you to the vertical and/or horizontal scroll direction without scroll bars.
This event has support in all current major browsers and should remain the standard far into the future.
Here is a demo:
window.addEventListener('wheel', function(event)
{
if (event.deltaY < 0)
{
console.log('scrolling up');
document.getElementById('status').textContent= 'scrolling up';
}
else if (event.deltaY > 0)
{
console.log('scrolling down');
document.getElementById('status').textContent= 'scrolling down';
}
});
<div id="status"></div>

Try This using addEventListener.
window.addEventListener('mousewheel', function(e){
wDelta = e.wheelDelta < 0 ? 'down' : 'up';
console.log(wDelta);
});
Demo
Update:
As mentioned in one of the answers, the mousewheel event is depreciated. You should use the wheel event instead.

I know this post is from 5 years ago but I didn't see any good Jquery answer (the .on('mousewheel') doesn't work for me...)
Simple answer with jquery, and use window instead of body to be sure you are taking scroll event :
$(window).on('wheel', function(e) {
var scroll = e.originalEvent.deltaY < 0 ? 'up' : 'down';
console.log(scroll);
});

Try using e.wheelDelta
var animationIsDone = false, scrollDirection = 0;
function preventScroll(e) {
e.preventDefault();
e.stopPropagation();
}
$('body').on('mousewheel', function(e) {
if (e.wheelDelta >= 0) {
console.log('Scroll up'); //your scroll data here
}
else {
console.log('Scroll down'); //your scroll data here
}
if (animationIsDone === false) {
$("#main-header").removeClass("yellow-overlay").addClass("yellow-overlay-darker");
$(".site-info").first().addClass("is-description-visible");
preventScroll(e);
setTimeout(function() {
animationIsDone = true;
}, 1000);
}
});
Note: remember that MouseWheel is deprecated and not supported in FireFox

this one work in react app
<p onWheel={this.onMouseWheel}></p>
after add event listener, in function u can use deltaY To capture mouse Wheel
onMouseWheel = (e) => {
e.deltaY > 0
? console.log("Down")
: console.log("up")
}

Tested on chrome and
$('body').on('mousewheel', function(e) {
if (e.originalEvent.deltaY >= 0) {
console.log('Scroll up'); //your scroll data here
}
else {
console.log('Scroll down'); //your scroll data here
}
});

Related

Scroll animation behaves erratically going up and down, possible input lag on mousewheel

I'm trying to trigger a smooth scroll to an element at the end of the page and another one to the top of the page everytime I move the mousewheel respectively down or up. The two parts have both height:100vh.
The thing is that once it goes down it starts to behave randomly.
I feel like I need to interrupt the animation completely after the scroll is completed because it "fights with itself" struggling to go back up and vice versa. Of course I could be easiy wrong, I'm trying to learn the way.
Is there some performance issue? Maybe it is unable to get the inputs in time? Something is overlapping? It seems like there's some sort of cooldown before I can scroll again. This is what I'm trying to understand. Thanks
jQuery(window).bind('mousewheel DOMMouseScroll', function(event){
if (event.originalEvent.wheelDelta > 0 || event.originalEvent.detail < 0) {
// scroll up
console.log("scroll up");
jQuery('html,body').animate({scrollTop: jQuery("#top").offset().top}, 1200, 'linear');
}
else {
// scroll down
console.log("scroll down");
jQuery('html,body').animate({scrollTop: jQuery("#bottom").offset().top}, 1200, 'linear');
}
});
Same thing with this, here I'm using the Jquery.scrollTo library
jQuery(window).bind('mousewheel DOMMouseScroll', function(event){
if (event.originalEvent.wheelDelta > 0 || event.originalEvent.detail < 0) {
// scroll up
console.log("scroll up");
jQuery('body').scrollTo('#top', {duration:1200});
}
else {
// scroll down
console.log("scroll down");
jQuery('body').scrollTo('#bottom', {duration:1200});
}
});
Here's the html for completeness:
<div id="top" style="height:100vh;background-color: #2196f3;"></div>
<div id="bottom" style="height:100vh;background-color: #009688;"></div>
EDIT:
If I move the mousewheel just the bare minimum it works perfectly both ways so the problem is input overlapping, in other words I need a way to send just the first scroll input and not the entire scroll otherwise too many inputs make the script "crash".
here's a working example, try to scroll up and down:
https://jsfiddle.net/mr8hnxbd/
Calling .stop(true) works, but I believe it might cause issues mid animation if you keep scrolling in the direction of the animation, extending the duration of the animation. Alternatively you can do the following to ensure the animation completes before doing another animation.
(function(jQuery) {
let position = '';
let scrolling = false;
let animationDuration = 1200;
jQuery(window).bind('mousewheel', function(event){
if (event.originalEvent.wheelDelta > 0) {
// scroll up
if (scrolling || position === 'top')
return;
//console.log("scroll up");
scrolling = true; //Prevents any scrolling when scrolling is active
position = 'top'; //Prevents scrolling up when already at the top
jQuery('html,body').animate(
{
scrollTop: jQuery("#top").offset().top
},
animationDuration,
'linear',
function () {
scrolling = false; //After the animation is complete, set scroling to false
},
);
}
else {
// scroll down
if (scrolling || position === 'bottom')
return;
//console.log("scroll down");
scrolling = true;
position = 'bottom';
jQuery('html,body').animate(
{
scrollTop: jQuery("#bottom").offset().top
},
animationDuration,
'linear',
function () {
scrolling = false;
},
);
}
});
})($);
<div id="top" style="height:100vh;background-color: #2196f3;"></div>
<div id="bottom" style="height:100vh;background-color: #009688;"></div>
<script src="https://code.jquery.com/jquery-3.6.0.min.js" integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=" crossorigin="anonymous"></script>

mousewheel event not working on firefox

Below code is working fine on chrome however it doesn't work on Mozilla for some reason that I am not aware yet. Am i missing something ?
$(window).bind('mousewheel', function(event) {
if (event.originalEvent.wheelDelta >= 0) {
$('#currentMove').html('Movement: Scroll up');
$('#currentMove').css('background','#98FB98');
scrollUp++;
$('#scrollUp').html(scrollUp);
}
else {
$('#currentMove').html('Movement: Scroll down');
$('#currentMove').css('background','#FFB6C1');
scrollDown++;
$('#scrollDown').html(scrollDown);
}
});
Here is my fiddle: https://jsfiddle.net/w0wffbxc/ Appreciate your help with this.
Here's your sqlfiddle fixed.
You should use wheel as mousewheel is not recognized by Firefox since version 3. Also with wheel, you should use event.originalEvent.deltaY instead.
Use wheel event instead. Its more of a standard now. This page also provides polyfills for old browsers https://developer.mozilla.org/en-US/docs/Web/Events/wheel
Ex
$(window).on('wheel', function(event){
// deltaY obviously records vertical scroll, deltaX and deltaZ exist too
if(event.originalEvent.deltaY < 0){
// wheeled up
console.log("Works Up");
}
else {
// wheeled down
console.log("Works Down");
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Scroll to specific div when scroll down or scroll up

On my site I have it so my scroll is locked:
body {
overflow: hidden;
height: 100%;
}
and on click of buttons it scrolls to a certain div, all the divs are beneath each other, I would like to know if it is possible to check if the user 'tries' to scroll down or up, while scroll is locked, so if they try scroll down with the mouse wheel, I want to know how to do this so I can scroll down or up to the next div.
Any help is appreciated.
This will tell you if they are scrolling down or up. Then you would have to deal with the transition by yourself.
But in any case, if you are looking for a more tested solution, I would encourage you to use an already existent plugin such as fullPage.js which will provide old browser compatibility, touch detection, a proper solution for trackpads and Apple laptops/Magic Mouse, resize support and a lot of other useful features.
addMouseWheelHandler();
function MouseWheelHandler(e) {
// cross-browser wheel delta
e = window.event || e;
var value = e.wheelDelta || -e.deltaY || -e.detail;
var delta = Math.max(-1, Math.min(1, value));
//scrolling down?
if (delta < 0) {
console.log("scrolling down");
}
//scrolling up?
else {
console.log("scrolling up");
}
return false;
}
function addMouseWheelHandler() {
if (document.addEventListener) {
document.addEventListener('mousewheel', MouseWheelHandler, false); //IE9, Chrome, Safari, Oper
document.addEventListener('wheel', MouseWheelHandler, false); //Firefox
} else {
document.attachEvent('onmousewheel', MouseWheelHandler); //IE 6/7/8
}
}

Get mouse wheel events in jQuery?

Is there a way to get the mouse wheel events (not talking about scroll events) in jQuery?
​$(document).ready(function(){
$('#foo').bind('mousewheel', function(e){
if(e.originalEvent.wheelDelta /120 > 0) {
console.log('scrolling up !');
}
else{
console.log('scrolling down !');
}
});
});
Binding to both mousewheel and DOMMouseScroll ended up working really well for me:
$(window).bind('mousewheel DOMMouseScroll', function(event){
if (event.originalEvent.wheelDelta > 0 || event.originalEvent.detail < 0) {
// scroll up
}
else {
// scroll down
}
});
This method is working in IE9+, Chrome 33, and Firefox 27.
Edit - Mar 2016
I decided to revisit this issue since it's been a while. The MDN page for the scroll event has a great way of retrieving the scroll position that makes use of requestAnimationFrame, which is highly preferable to my previous detection method. I modified their code to provide better compatibility in addition to scroll direction and position:
(function() {
var supportOffset = window.pageYOffset !== undefined,
lastKnownPos = 0,
ticking = false,
scrollDir,
currYPos;
function doSomething(scrollPos, scrollDir) {
// Your code goes here...
console.log('scroll pos: ' + scrollPos + ' | scroll dir: ' + scrollDir);
}
window.addEventListener('wheel', function(e) {
currYPos = supportOffset ? window.pageYOffset : document.body.scrollTop;
scrollDir = lastKnownPos > currYPos ? 'up' : 'down';
lastKnownPos = currYPos;
if (!ticking) {
window.requestAnimationFrame(function() {
doSomething(lastKnownPos, scrollDir);
ticking = false;
});
}
ticking = true;
});
})();
See the Pen Vanilla JS Scroll Tracking by Jesse Dupuy (#blindside85) on CodePen.
This code is currently working in Chrome v50, Firefox v44, Safari v9, and IE9+
References:
https://developer.mozilla.org/en-US/docs/Web/Events/scroll
https://developer.mozilla.org/en-US/docs/Web/Events/wheel
As of now in 2017, you can just write
$(window).on('wheel', function(event){
// deltaY obviously records vertical scroll, deltaX and deltaZ exist too.
// this condition makes sure it's vertical scrolling that happened
if(event.originalEvent.deltaY !== 0){
if(event.originalEvent.deltaY < 0){
// wheeled up
}
else {
// wheeled down
}
}
});
Works with current Firefox 51, Chrome 56, IE9+
There's a plugin that detects up/down mouse wheel and velocity over a region.
Answers talking about "mousewheel" event are refering to a deprecated event. The standard event is simply "wheel". See https://developer.mozilla.org/en-US/docs/Web/Reference/Events/wheel
This worked for me:)
//Firefox
$('#elem').bind('DOMMouseScroll', function(e){
if(e.originalEvent.detail > 0) {
//scroll down
console.log('Down');
}else {
//scroll up
console.log('Up');
}
//prevent page fom scrolling
return false;
});
//IE, Opera, Safari
$('#elem').bind('mousewheel', function(e){
if(e.originalEvent.wheelDelta < 0) {
//scroll down
console.log('Down');
}else {
//scroll up
console.log('Up');
}
//prevent page fom scrolling
return false;
});
from stackoverflow
Here is a vanilla solution. Can be used in jQuery if the event passed to the function is event.originalEvent which jQuery makes available as property of the jQuery event. Or if inside the callback function under we add before first line: event = event.originalEvent;.
This code normalizes the wheel speed/amount and is positive for what would be a forward scroll in a typical mouse, and negative in a backward mouse wheel movement.
Demo: http://jsfiddle.net/BXhzD/
var wheel = document.getElementById('wheel');
function report(ammout) {
wheel.innerHTML = 'wheel ammout: ' + ammout;
}
function callback(event) {
var normalized;
if (event.wheelDelta) {
normalized = (event.wheelDelta % 120 - 0) == -0 ? event.wheelDelta / 120 : event.wheelDelta / 12;
} else {
var rawAmmount = event.deltaY ? event.deltaY : event.detail;
normalized = -(rawAmmount % 3 ? rawAmmount * 10 : rawAmmount / 3);
}
report(normalized);
}
var event = 'onwheel' in document ? 'wheel' : 'onmousewheel' in document ? 'mousewheel' : 'DOMMouseScroll';
window.addEventListener(event, callback);
There is also a plugin for jQuery, which is more verbose in the code and some extra sugar: https://github.com/brandonaaron/jquery-mousewheel
This is working in each IE, Firefox and Chrome's latest versions.
$(document).ready(function(){
$('#whole').bind('DOMMouseScroll mousewheel', function(e){
if(e.originalEvent.wheelDelta > 0 || e.originalEvent.detail < 0) {
alert("up");
}
else{
alert("down");
}
});
});
I was stuck in this issue today and found this code is working fine for me
$('#content').on('mousewheel', function(event) {
//console.log(event.deltaX, event.deltaY, event.deltaFactor);
if(event.deltaY > 0) {
console.log('scroll up');
} else {
console.log('scroll down');
}
});
use this code
knob.bind('mousewheel', function(e){
if(e.originalEvent.wheelDelta < 0) {
moveKnob('down');
} else {
moveKnob('up');
}
return false;
});
The plugin that #DarinDimitrov posted, jquery-mousewheel, is broken with jQuery 3+. It would be more advisable to use jquery-wheel which works with jQuery 3+.
If you don't want to go the jQuery route, MDN highly cautions using the mousewheel event as it's nonstandard and unsupported in many places. It instead says that you should use the wheel event as you get much more specificity over exactly what the values you're getting mean. It's supported by most major browsers.
my combination looks like this. it fades out and fades in on each scroll down/up. otherwise you have to scroll up to the header, for fading the header in.
var header = $("#header");
$('#content-container').bind('mousewheel', function(e){
if(e.originalEvent.wheelDelta > 0) {
if (header.data('faded')) {
header.data('faded', 0).stop(true).fadeTo(800, 1);
}
}
else{
if (!header.data('faded')) header.data('faded', 1).stop(true).fadeTo(800, 0);
}
});
the above one is not optimized for touch/mobile, I think this one does it better for all mobile:
var iScrollPos = 0;
var header = $("#header");
$('#content-container').scroll(function () {
var iCurScrollPos = $(this).scrollTop();
if (iCurScrollPos > iScrollPos) {
if (!header.data('faded')) header.data('faded', 1).stop(true).fadeTo(800, 0);
} else {
//Scrolling Up
if (header.data('faded')) {
header.data('faded', 0).stop(true).fadeTo(800, 1);
}
}
iScrollPos = iCurScrollPos;
});
If using mentioned jquery mousewheel plugin, then what about to use the 2nd argument of event handler function - delta:
$('#my-element').on('mousewheel', function(event, delta) {
if(delta > 0) {
console.log('scroll up');
}
else {
console.log('scroll down');
}
});
I think many key things are a bit all over the place and I needed to read all the answers to make my code work as I wanted, so I will post my findings in just one place:
You should use "wheel" event over the other deprecated or browser specific events.
Many people here is getting something wrong: the opposite of x>0 is x<=0 and the opposite of x<0 is x>=0, many of the answers in here will trigger scrolling down or up incorrectly when x=0 (horizontal scrolling).
Someone was asking how to put sensitivity on it, for this you can use setTimeout() with like 50 ms of delay that changes some helper flag isWaiting=false and you protect yourself with if(isWaiting) then don't do anything. When it fires you manually change isWaiting=true and just below this line you start the setTimeout again who will later change isWaiting=false after 50 ms.
I got same problem recently where
$(window).mousewheel was returning undefined
What I did was $(window).on('mousewheel', function() {});
Further to process it I am using:
function (event) {
var direction = null,
key;
if (event.type === 'mousewheel') {
if (yourFunctionForGetMouseWheelDirection(event) > 0) {
direction = 'up';
} else {
direction = 'down';
}
}
}

Distinguishing between the user scrolling and programmatically scrolling using Javascript

I'm creating a scrolling effect using JQuery and I'm wondering if it's possible to distinguish between the user scrolling vs. programmatically scrolling.
I have something like this:
$('#element').on('scroll',function(e){
$('#element').stop(true); // stop previous scrolling animation
$('#element').animate({ // start new scrolling animation (maybe different speed, different direction, etc)
scrollTop:...
});
});
However, this event is triggered during every step of the animation. How can I tell if this event was triggered by the user or by the animation?
Use a variable to determine when you are scrolling programmatically
Example:
var programScrolling = false;
$('#element').on('scroll',function(e){
if (programScrolling) {
return;
}
$('#element').stop(true); // stop scrolling animation
programScrolling = true;
$('#element').animate({
scrollTop:...
});
programScrolling = false;
});
Not sure if that is exactly what you want, but the concept should work.
I would make functions for different kinds of scrollings to detect them and call a scroll handler for all of them, like so:
JS Fiddle
$(window).bind('mousewheel DOMMouseScroll', function(event){
var direction;
if (event.originalEvent.wheelDelta > 0 || event.originalEvent.detail < 0) {
direction = 'up';
}
else {
direction = 'down';
}
scrollHandler(direction, 'mouseWheel');
event.preventDefault();
});
var scrollHandler = function(direction, origin) {
var height = $(document).scrollTop();
var movement = (direction == 'up') ? -100 : 100;
console.log(origin);
$('body').stop(true);
$('body').animate({
scrollTop: height + movement
}, 250);
};
Then you can do different stuff according to the origin of the event!
You could also check if the user scrolls to the same direction that the screen is scrolling and do something different, or whatever you want with the info passed by the mousewheel event.
Original mousewheel event function copied from THIS answer
I would suggest possibly using the .originalEvent method. The downside is, this is very browser dependent. See here. Hopefully the following helps:
$('#element').scroll(function(e){
var humanScroll = e.originalEvent === undefined;
if(humanScroll) {
$(this).stop(true);
}
})

Categories

Resources