So I'm trying to disable scrolling on my page when my lightbox opens, and I found this really usefull script that does exactly that. (http://jsfiddle.net/mrtsherman/eXQf3/3/), unfortunately, when I use it on my own page, it disabled scrolling in my lightbox as well. I started to debug the code with alerts only to find out that event.wheelDelta returns "undefined" on my page, while in the JSFiddle, it returns -120.
The event object in a jQuery event handler does not reflect the real event. wheelDelta is a non-standard event propertyIE and Opera, available through the originalEvent property of the jQuery event.
In jQuery 1.7+, the detail property is not available at the jQuery Event object. So, you should also use event.originalEvent.detail to for this property at the DOMMouseScroll event. This method is backwards-compatible with older jQuery versions.
event.originalEvent.wheelDelta
Demo: http://jsfiddle.net/eXQf3/22/
See also: http://api.jquery.com/category/events/event-object/
$.fn.wheel = function (callback) {
return this.each(function () {
$(this).on('mousewheel DOMMouseScroll', function (e) {
e.delta = null;
if (e.originalEvent) {
if (e.originalEvent.wheelDelta) e.delta = e.originalEvent.wheelDelta / -40;
if (e.originalEvent.deltaY) e.delta = e.originalEvent.deltaY;
if (e.originalEvent.detail) e.delta = e.originalEvent.detail;
}
if (typeof callback == 'function') {
callback.call(this, e);
}
});
});
};
and use like this:
$('body').wheel(function (e) {
e.preventDefault();
$('#myDiv').append($('<div>').text(e.delta));
});
big thx to #Mark for jquery-fying the function (:
$(this).on('mousewheel DOMMouseScroll', function(e){
var dat = $(e.delegateTarget).data(); //in case you have set some, read it here.
var datx = dat.x || 0; // just to show how to get specific out of jq-data object
var eo = e.originalEvent;
var xy = eo.wheelDelta || -eo.detail; //shortest possible code
var x = eo.wheelDeltaX || (eo.axis==1?xy:0);
var y = eo.wheelDeltaY || (eo.axis==2?xy:0); // () necessary!
console.log(x,y);
});
works in Webkit and FF, can not proof IE here :(
When I need WheelDelta, I pass the event along to this little gem...
function getWheelDelta(event) {
return event.wheelDelta || -event.detail || event.originalEvent.wheelDelta || -event.originalEvent.detail || -(event.originalEvent.deltaY * 25) || null;
}
Example jQuery where I used it to obtain the delta for scrolling elements with the overflow:hidden CSS rule...
$('#parent-id').on('wheel mousewheel DOMMouseScroll', function(event) {
var node = $('#child-id');
node.prop('scrollTop', parseFloat(node.prop('scrollTop')) - (getWheelDelta(event) / 2));
return false;
});
Note: Reverse scroll direction by adding delta instead of subtracting like example above.
I have tried your solution, psycho brm, and I have changed the function extractDelta(e) to make it works in Firefox. Instead of e.detail I have used e.originalEvent.detail because Firefox returned an undefined delta. I have uploaded the solution and my test code to this post. I hope it helps.
function extractDelta(e) {
if (e.wheelDelta) {
return e.wheelDelta;
}
if (e.originalEvent.detail) {
return e.originalEvent.detail * -40;
}
if (e.originalEvent && e.originalEvent.wheelDelta) {
return e.originalEvent.wheelDelta;
}
}
Related
I made a script to register the thumb scroll wheel event (MX Master 2S if you're wondering). However, this script ran perfectly fine in Chrome, but not in Firefox (Quantum). Why is that so?
var expression = /[-a-zA-Z0-9#:%_\+.~#?&//=]{2,256}\.[a-z]{2,4}\b(\/[-a-zA-Z0-9#:%_\+.~#?&//=]*)?/gi;
var regex = new RegExp(expression);
var elements = document.getElementsByClassName('pagination'); // get the elements
var search = (elements[0].innerHTML.match(regex));
//alert(search);
if(document.addEventListener){
document.addEventListener("mousewheel", MouseWheelHandler, false);
document.addEventListener("DOMMouseScroll", MouseWheelHandler, false);
} else {
document.attachEvent("onmousewheel", MouseWheelHandler);
}
function MouseWheelHandler(e) {
var e = window.event || e;
var ret = true;
if (e.wheelDelta) {
// Tilt to the left
if (e.wheelDeltaX < 0) {
str = window.location.toString();
strsplit = str.split('/');
preloc=Number(strsplit[4])+1;
if (preloc > 0) {
window.location.replace("https://somepage.com/page/"+preloc);}
prelocstr=preloc.toString();
if (prelocstr == "NaN") {
window.location.replace(search[0]); }
ret = false;
}
// Tilt to the right
if (e.wheelDeltaX > 0) {
str = window.location.toString();
strsplit = str.split('/');
preloc=Number(strsplit[4])-1;
if (preloc > 0) {
window.location.replace("https://somepage.com/page/"+preloc);}
ret = false;
}
}
event.returnValue = ret;
}
This script is made within Tampermonkey. Could anyone point me the mistake? Thanks in advance!
There's a newer standard for handling mouse wheel event that's standard across browsers:
https://developer.mozilla.org/en-US/docs/Web/API/WheelEvent
https://developer.mozilla.org/en-US/docs/Web/Events/wheel
To use this event, do:
document.addEventListener("wheel", MouseWheelHandler);
And there's no need for:
e = window.event || e
The event will be there.
Only DOMMouseScroll works with Firefox, but it uses a different API. So, you have to write a separate handler for Firefox, instead of using the MouseWheelHandler, or adjust the MouseWheelHandler to support both.
As kshetline pointed out, there is now a new standard, which works with all modern browsers: https://developer.mozilla.org/en-US/docs/Web/API/WheelEvent.
The other two options don't work in Firefox, as stated here:
This feature is non-standard and is not on a standards track. Do not
use it on production sites facing the Web: it will not work for every
user. There may also be large incompatibilities between
implementations and the behavior may change in the future.
Source: https://developer.mozilla.org/en-US/docs/Web/Events/mousewheel
While looking for how to enable scrolling with the mouse wheel in Sencha Touch, I came across this answer. However, I am relatively new to Sencha Touch and the codebase I was given to maintain that uses it.
The answer says to put it in the initialization block of my application: as far as I can tell, that would be my app.js file that is generated by Sencha Cmd (which has a launch function). However, I'm lost after this. Would I add the first part of the above answer in the launch block? Outside of it? How would I make sure that it is automatically called on every page?
Edit: Here is my app.js file, in case it helps.
Ext.application({
name: 'App',
requires: [
'Ext.MessageBox',
'Ext.direct.*'
],
models:[
"..."
],
controllers: [
'...',
'...',
'...'
],
icon: {
'57': 'resources/icons/Icon.png',
'72': 'resources/icons/Icon~ipad.png',
'114': 'resources/icons/Icon#2x.png',
'144': 'resources/icons/Icon~ipad#2x.png'
},
isIconPrecomposed: true,
startupImage: {
'320x460': 'resources/startup/320x460.jpg',
'640x920': 'resources/startup/640x920.png',
'768x1004': 'resources/startup/768x1004.png',
'748x1024': 'resources/startup/748x1024.png',
'1536x2008': 'resources/startup/1536x2008.png',
'1496x2048': 'resources/startup/1496x2048.png'
},
profiles: ['Tablet', 'Phone'],
launch: function() {
...
}
....
});
Edit 2: I am using Sencha Touch 2.3.
The provided code in the other answer is pure Javascript and not ExtJs code, it runs in a global scope so you can add this above Ext.application (outside of ExtJs code, so make it your first bit of JS code that gets run). You could even wrap it inside an Ext.onReady call to make sure ExtJs is also fully loaded before you add it, if needed.
This should work, it might be worth looking over the Sencha forums or even on here for a more elegant and updated solution though.
The OP's answer above works, however it throws errors if trying to scroll over elements that do not have indexOf on their className (like SVG elements). Here is the updated code that first checks for the existence of indexOf.
I've also extended this method to support horizontal mouse scrolling if the browser supports wheelDeltaX and wheelDeltaY. Otherwise it defaults to using the more widely available wheelDelta and only scrolls in the Y direction.
Note that you can embed this code in a function and simply call it during the launch of your app. No need to put it at the top of the app.js file.
var mouseWheelHandler = function (e) {
var e = window.event || e,
el = e.target,
cmp,
offset,
scroller,
deltaY,
deltaX,
_results = [];
e.preventDefault(); // prevent scrolling when in iframe
while (el !== document.body) {
if (el && el.className && el.className.indexOf && el.className.indexOf('x-container') >= 0) {
cmp = Ext.getCmp(el.id);
if (cmp && typeof cmp.getScrollable == 'function' && cmp.getScrollable()) {
scroller = cmp.getScrollable().getScroller();
if (scroller) {
deltaY = e.detail ? e.detail * (-120) : e.hasOwnProperty('wheelDeltaY') ? e.wheelDeltaY : e.wheelDelta;
deltaX = e.detail ? e.detail * (-120) : e.hasOwnProperty('wheelDeltaX') ? e.wheelDeltaX : 0;
offset = {x: -deltaX * 0.5, y: -deltaY * 0.5};
scroller.fireEvent('scrollstart', scroller, scroller.position.x, scroller.position.y, e);
scroller.scrollBy(offset.x, offset.y);
scroller.snapToBoundary();
scroller.fireEvent('scrollend', scroller, scroller.position.x + offset.x, scroller.position.y - offset.y);
break;
}
}
}
_results.push(el = el.parentNode);
}
return _results;
};
if (document.addEventListener) {
// IE9, Chrome, Safari, Opera
document.addEventListener('mousewheel', mouseWheelHandler, false);
// Firefox
document.addEventListener('DOMMouseScroll', mouseWheelHandler, false);
}
else {
// IE 6/7/8
document.attachEvent('onmousewheel', mouseWheelHandler);
}
}
Thanks user991710 and Scriptable for your answer. In my case i added the entire code within the Ext.onReady event because it didn't work in the app.js.
Below is how i have incorporated the code in the Ext.onReady in the default.js
onReady: function() {
if (this.getAutoRender()) {
this.render();
}
if (Ext.browser.name == 'ChromeiOS') {
this.setHeight('-webkit-calc(100% - ' + ((window.outerHeight - window.innerHeight) / 2) + 'px)');
}
/* code ten behoeve van mousescroll in Chrome situatie */
var mouseWheelHandler = function (e) {
var e = window.event || e,
el = e.target,
cmp,
offset,
scroller,
delta,
_results = [];
e.preventDefault(); // prevent scrolling when in iframe
while (el !== document.body) {
if (el && el.className && el.className.indexOf('x-container') >= 0) {
cmp = Ext.getCmp(el.id);
if (cmp && typeof cmp.getScrollable == 'function' && cmp.getScrollable()) {
scroller = cmp.getScrollable().getScroller();
if (scroller) {
delta = e.detail ? e.detail * (-120) : e.wheelDelta;
offset = { x: 0, y: -delta * 0.5 };
scroller.fireEvent('scrollstart', scroller, scroller.position.x, scroller.position.y, e);
scroller.scrollBy(offset.x, offset.y);
scroller.snapToBoundary();
scroller.fireEvent('scrollend', scroller, scroller.position.x, scroller.position.y - offset.y);
break;
}
}
}
_results.push(el = el.parentNode);
}
return _results;
};
if (document.addEventListener) {
// IE9, Chrome, Safari, Opera
document.addEventListener('mousewheel', mouseWheelHandler, false);
// Firefox
document.addEventListener('DOMMouseScroll', mouseWheelHandler, false);
}
else {
// IE 6/7/8
document.attachEvent('onmousewheel', mouseWheelHandler);
}
/*einde code ten behoeve van muisscroll in Chrome modus */
},
Solution by OP.
In my app.js file (the one generated by Sencha Cmd), I added the following code at the very top of the file, before my Ext.application definition:
var mouseWheelHandler = function (e) {
var e = window.event || e,
el = e.target,
cmp,
offset,
scroller,
delta,
_results = [];
e.preventDefault(); // prevent scrolling when in iframe
while (el !== document.body) {
if (el && el.className && el.className.indexOf('x-container') >= 0) {
cmp = Ext.getCmp(el.id);
if (cmp && typeof cmp.getScrollable == 'function' && cmp.getScrollable()) {
scroller = cmp.getScrollable().getScroller();
if (scroller) {
delta = e.detail ? e.detail*(-120) : e.wheelDelta;
offset = { x:0, y: -delta*0.5 };
scroller.fireEvent('scrollstart', scroller, scroller.position.x, scroller.position.y, e);
scroller.scrollBy(offset.x, offset.y);
scroller.snapToBoundary();
scroller.fireEvent('scrollend', scroller, scroller.position.x, scroller.position.y-offset.y);
break;
}
}
}
_results.push(el = el.parentNode);
}
return _results;
};
if (document.addEventListener) {
// IE9, Chrome, Safari, Opera
document.addEventListener('mousewheel', mouseWheelHandler, false);
// Firefox
document.addEventListener('DOMMouseScroll', mouseWheelHandler, false);
}
Credit to the above code goes to user m.dostal on the Sencha Touch forums. If you happen across this solution, please upvote user Scriptable below as he helped me find the correct solution.
Good day all.
I'm having some problems with hoverintent.js a jquery plugin that handle the mouseOver events in a different way than normal.
Due to some complications, I can't modifiy anything but the js of this plugin, but I need to make it compliant with touch events and not only with mouseOver and mouseLeave.
after some debugs, I have managed to recognize this part of the code to be the one to modify:
var handleHover = function(e) {
// next three lines copied from jQuery.hover, ignore children onMouseOver/onMouseOut
var p = (e.type == "mouseover" ? e.fromElement : e.toElement) || e.relatedTarget;
while ( p && p != this ) { try { p = p.parentNode; } catch(e) { p = this; } }
if ( p == this ) { return false; }
// copy objects to be passed into t (required for event object to be passed in IE)
var ev = jQuery.extend({},e);
var ob = this;
// cancel hoverIntent timer if it exists
if (ob.hoverIntent_t) { ob.hoverIntent_t = clearTimeout(ob.hoverIntent_t); }
// else e.type == "onmouseover"
if (e.type == "mouseover") {
// set "previous" X and Y position based on initial entry point
pX = ev.pageX; pY = ev.pageY;
// update "current" X and Y position based on mousemove
$(ob).bind("mousemove",track);
// start polling interval (self-calling timeout) to compare mouse coordinates over time
if (ob.hoverIntent_s != 1) { ob.hoverIntent_t = setTimeout( function(){compare(ev,ob);} , cfg.interval );}
// else e.type == "onmouseout"
} else {
// unbind expensive mousemove event
$(ob).unbind("mousemove",track);
// if hoverIntent state is true, then call the mouseOut function after the specified delay
if (ob.hoverIntent_s == 1) { ob.hoverIntent_t = setTimeout( function(){delay(ev,ob);} , cfg.timeout );}
}
}
};
// bind the function to the two event listeners
return this.mouseover(handleHover).mouseout(handleHover);
what I've done so far is to make the function working different with mobiles:
var handleHover = function(e) {
isMobile = /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent);
if(isMobile){
console.log("Ismobile");
}else{
... Same code as before here ...
}
// bind the function to the two event listeners
return this.mouseover(handleHover).mouseout(handleHover);
and now i'm struck. I would like it to "change" its behavior to handle the touch, and not the mouse over event, so on mobiles I will need to touch the element, instead to hovering on it. May someone give me an help? Am I on the right way? Is it the right way to think of it?
unluckily I have only the possibility to change this file and some few more.
Recently i bumped into several problems with changing hoverIntent.js, and ended up in writing my own plugin: hoverDelay.js (much simpler, and less code). see if you can use it, and modify it to your own needs (and maybe contribute the mobile code to it :-)
Here is an interesting jsfiddle.
In Firefox:
Run the fiddle
Click in text input
Click somewhere else. Should say "1 blurs".
Click in the text input again.
ALT-TAB to another window. Fiddle should now say "2 blurs".
In Chrome, at step 5, it says "3 blurs". Two separate "blur" events are fired when the whole browser loses focus. This is of interest because it means that it's not safe to assume, in a "blur" handler, that the element actually had focus just before the event was dispatched; that is, that the loss of focus — the transition from "being in focus" to "not being in focus" — is the reason for the event. When two "blur" events are generated, that condition is not satisfied during the handling of the second event, as the element is already not in focus.
So is this just a bug? Is there a way to tell that a "blur" event is bogus?
The reason it is firing twice is because of window.onblur. The window blurring triggers a blur event on all elements in that window as part of the way javascript's capturing/bubbling process. All you need to do is test the event target for being the window.
var blurCount = 0;
var isTargetWindow = false;
$(window).blur(function(e){
console.log(e.target);
isTargetWindow = true;
});
$(window).focus(function(){
isTargetWindow = false;
});
$('input').blur(function(e) {
if(!isTargetWindow){
$('div').text(++blurCount + ' blurs');
}
console.log(e.target);
});
http://jsfiddle.net/pDYsM/4/
This is confirmed Chrome bug. See the Chromium Issue Tracker
The workaround is in the accepted answer.
Skip 2nd blur:
var secondBlur = false;
this.onblur = function(){
if(secondBlur)return;
secondBlur = true;
//do whatever
}
this.onfocus = function(){
secondBlur = false;
//do whatever
}
This probably isn't what you want to hear, but the only way to do it seems to be to manually track whether the element is focused or not. For example (fiddle here):
var blurCount = 0;
document.getElementsByTagName('input')[0].onblur = function(e) {
if (!e) e = window.event;
console.log('blur', e);
if (!(e.target || e.srcElement)['data-focused']) return;
(e.target || e.srcElement)['data-focused'] = false;
document.getElementsByTagName('div')[0].innerHTML = (++blurCount + ' blurs');
};
document.getElementsByTagName('input')[0].onfocus = function(e) {
if (!e) e = window.event;
console.log('focus', e);
(e.target || e.srcElement)['data-focused'] = true;
};
Interestingly, I couldn't get this to work in jQuery (fiddle here) ... I really don't use jQuery much, maybe I'm doing something wrong here?
var blurCount = 0;
$('input').blur(function(e) {
console.log('blur', e);
if (!(e.target || e.srcElement)['data-focused']) return;
(e.target || e.srcElement)['data-focused'] = false;
$('div').innerHTML = (++blurCount + ' blurs');
});
$('input').focus(function(e) {
console.log('focus', e);
(e.target || e.srcElement)['data-focused'] = true;
});
You could also try comparing the event's target with document.activeElement. This example will ignore the alt+tab blur events, and the blur events resulting from clicking on Chrome's... chrome. This could be useful depending on the situation. If the user alt+tabs back into Chrome, it's as if the box never lost focus (fiddle).
var blurCount = 0;
document.getElementsByTagName('input')[0].onblur = function(e) {
if (!e) e = window.event;
console.log('blur', e, document.activeElement, (e.target || e.srcElement));
if ((e.target || e.srcElement) == document.activeElement) return;
document.getElementsByTagName('div')[0].innerHTML = (++blurCount + ' blurs');
};
I'm on Chrome Version 30.0.1599.101 m on Windows 7 and this issue appears to have been fixed.
I am experiencing the same and the above posts make sense as to why. In my case I just wanted to know if at least one blur event had occurred. As a result I found that just returning from my blur function solved my issue and prevented the subsequent event from firing.
function handleEditGroup(id) {
var groupLabelObject = $('#' + id);
var originalText = groupLabelObject.text();
groupLabelObject.attr('contenteditable', true)
.focus().blur(function () {
$(this).removeAttr('contenteditable');
$(this).text($(this).text().substr(0, 60));
if ($(this).text() != originalText) {
alert("Change Found");
return; //<--- Added this Return.
}
});
}
Looks like an oddity of angularjs gives a simpler solution when using ng-blur; the $event object is only defined if you pass it in:
ng-blur="onBlur($event)"
so (if you aren't using ng-blur on the window) you can check for:
$scope.onBlur = function( $event ) {
if (event != undefined) {
//this is the blur on the element
}
}
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';
}
}
}