I'm messing around with touch events on a touch slider and I keep getting the following error:
Ignored attempt to cancel a touchmove event with cancelable=false,
for example because scrolling is in progress and cannot be
interrupted.
I'm not sure what is causing this problem, I am new to working with touch events and can't seem to fix this problem.
Here is the code handling the touch event:
Slider.prototype.isSwipe = function(threshold) {
return Math.abs(deltaX) > Math.max(threshold, Math.abs(deltaY));
}
Slider.prototype.touchStart = function(e) {
if (this._isSliding) return false;
touchMoving = true;
deltaX = deltaY = 0;
if (e.originalEvent.touches.length === 1) {
startX = e.originalEvent.touches[0].pageX;
startY = e.originalEvent.touches[0].pageY;
this._$slider.on('touchmove touchcancel', this.touchMove.bind(this)).one('touchend', this.touchEnd.bind(this));
isFlick = true;
window.setTimeout(function() {
isFlick = false;
}, flickTimeout);
}
}
Slider.prototype.touchMove = function(e) {
deltaX = startX - e.originalEvent.touches[0].pageX;
deltaY = startY - e.originalEvent.touches[0].pageY;
if(this.isSwipe(swipeThreshold)) {
e.preventDefault();
e.stopPropagation();
swiping = true;
}
if(swiping) {
this.slide(deltaX / this._sliderWidth, true)
}
}
Slider.prototype.touchEnd = function(e) {
var threshold = isFlick ? swipeThreshold : this._sliderWidth / 2;
if (this.isSwipe(threshold)) {
deltaX < 0 ? this.prev() : this.next();
}
else {
this.slide(0, !deltaX);
}
swiping = false;
this._$slider.off('touchmove', this.touchMove).one(transitionend, $.proxy(function() {
this.slide(0, true);
touchMoving = false;
}, this));
}
You can find the actual slider here at this pen.
If you swipe through fast enough it will throw the error and sometimes get stuck in the middle of a swipe. Still can't wrap my head around why it is not working. Any help/insight would be greatly appreciated. Not sure what I am doing wrong.
The event must be cancelable. Adding an if statement solves this issue.
if (e.cancelable) {
e.preventDefault();
}
In your code you should put it here:
if (this.isSwipe(swipeThreshold) && e.cancelable) {
e.preventDefault();
e.stopPropagation();
swiping = true;
}
I know this is an old post but I had a lot of issues trying to solve this and I finally did so I wanted to share.
My issue was that I was adding an event listener within the ontouchstart and removing it in the ontouchend functions - something like this
function onTouchStart() {
window.addEventListener("touchmove", handleTouchMove, {
passive: false
});
}
function onTouchEnd() {
window.removeEventListener("touchmove", handleTouchMove, {
passive: true
});
}
function handleTouchMove(e) {
e.preventDefault();
}
For some reason adding it removing it like this was causing this issue of the event randomly not being cancelable. So to solve this I kept the listener active and toggled a boolean on whether or not it should prevent the event - something like this:
let stopScrolling = false;
window.addEventListener("touchmove", handleTouchMove, {
passive: false
});
function handleTouchMove(e) {
if (!stopScrolling) {
return;
}
e.preventDefault();
}
function onTouchStart() {
stopScrolling = true;
}
function onTouchEnd() {
stopScrolling = false;
}
I was actually using React so my solution involved setting state, but I've simplified it for a more generic solution. Hopefully this helps someone!
I had this problem and all I had to do is return true from touchend and the warning went away.
Calling preventDefault on touchmove while you're actively scrolling is not working in Chrome. To prevent performance issues, you cannot interrupt a scroll.
Try to call preventDefault() from touchstart and everything should be ok.
Please remove e.preventDefault(), because event.cancelable of touchmove is false.
So you can't call this method.
If it is an image, you can just set 'touch-action' to none in css.
Related
I have circle menu with rotation. And after simple click i want to fire click event, but during rotation - mousemove i want ignore click. For now i have -
<g id="bottomMenuRotate" onMouseDown={this.selectElement.bind(this)}>
Then my select function looks -
selectElement(e){
let groupRotate = document.getElementById('bottomMenuRotate');
groupRotate.onmousemove = function(e) {....}
groupRotate.onmouseup = function(e){
groupRotate.onmousemove = null;
}
}
So how i cant prevent click? I tried something like
groupRotate.onmouseup = function(e){
e.stopPropagation();
groupRotate.onmousemove = null;
};
or
groupRotate.onmouseclick = function(e){
e.stopPropagation();
}
but this prevents every click. Any tips how i can do it?
So i finally found simply solution
selectElement(e){
let move = false;
groupRotate.onmousemove = function(e) {
move = true;
}
groupRotate.onclick = function(e){
move ? e.preventDefault() : false;
}
}
This prevent click only when move is set to true.
Set a state in your onMouseMove handler that prevents the click events from running:
groupRotate.onmousemove = (e) => {
this.setState({ mouseMoving: true });
}
groupRotate.onmouseup = (e) => {
this.setState({ mouseMoving: false });
}
Somewhere else:
groupRotate.onmouseclick = (e) => {
if (!this.state.mouseMoving) {
...
};
}
Note the arrow functions to make this available within the functions.
I have to implement mouse move event only when mouse down is pressed.
I need to execute "OK Moved" only when mouse down and mouse move.
I used this code
$(".floor").mousedown(function() {
$(".floor").bind('mouseover',function(){
alert("OK Moved!");
});
})
.mouseup(function() {
$(".floor").unbind('mouseover');
});
Use the mousemove event.
From mousemove and mouseover jquery docs:
The mousemove event is sent to an element when the mouse pointer moves inside the element.
The mouseover event is sent to an element when the mouse pointer enters the element.
Example: (check console output)
$(".floor").mousedown(function () {
$(this).mousemove(function () {
console.log("OK Moved!");
});
}).mouseup(function () {
$(this).unbind('mousemove');
}).mouseout(function () {
$(this).unbind('mousemove');
});
https://jsfiddle.net/n4820hsh/
In pure javascript, you can achieve this with
function mouseMoveWhilstDown(target, whileMove) {
var endMove = function () {
window.removeEventListener('mousemove', whileMove);
window.removeEventListener('mouseup', endMove);
};
target.addEventListener('mousedown', function (event) {
event.stopPropagation(); // remove if you do want it to propagate ..
window.addEventListener('mousemove', whileMove);
window.addEventListener('mouseup', endMove);
});
}
Then using the function along the lines of
mouseMoveWhilstDown(
document.getElementById('move'),
function (event) { console.log(event); }
);
(nb: in the above example, you don't need the function - you could call it as mouseMoveWhilstDown(document.getElementById('move'), console.log), but you might want to do something with it other than output it to the console!)
I know that this issue was submitted and resolved approximately seven years ago, but there is a simpler solution now:
element.addEventListener('mousemove', function(event) {
if(event.buttons == 1) {
event.preventDefault();
// Your code here!
}
});
or for touch compatible devices:
element.addEventListener('touchmove', function(event) {
if(event.touches.length == 1) {
event.preventDefault();
// Your code here!
}
}
For more information on MouseEvent.buttons, click here to visit MDN Web Docs. Touch compatible devices, however, tend to listen to TouchEvents instead of MouseEvents. TouchEvent.touches.length achieves a similar effect to MouseEvent.buttons.
To provide an example, I used the following code to move an element I created. For moving an element, I used the 'mousemove' event's MouseEvent.movementX and MouseEvent.movementY to simplify the code. The 'touchmove' event does not have these so I stored the previous touch coordinates and cleared them on 'touchstart'. You can do something similar for the 'mousemove' event if desired, as the movementX and movementY values may vary across browsers.
document.addEventListener('DOMContentLoaded', () => {
var element = document.getElementById('box');
element.style.position = 'fixed';
// MouseEvent solution.
element.addEventListener('mousemove', function(event) {
if(event.buttons == 1) {
event.preventDefault();
this.style.left = (this.offsetLeft+event.movementX)+'px';
this.style.top = (this.offsetTop+event.movementY)+'px';
}
});
// TouchEvent solution.
element.addEventListener('touchstart', function(event) {
/* Elements do not have a 'previousTouch' property. I create
this property during the touchmove event to store and
access the previous touchmove event's touch coordinates. */
delete this.previousTouch;
});
element.addEventListener('touchmove', function(event) {
if(event.touches.length == 1) {
event.preventDefault();
if(typeof this.previousTouch == 'object') {
this.style.left = (this.offsetLeft+event.touches[0].pageX-this.previousTouch.x)+'px';
this.style.top = (this.offsetTop+event.touches[0].pageY-this.previousTouch.y)+'px';
}
this.previousTouch = {
x: event.touches[0].pageX,
y: event.touches[0].pageY
};
}
});
});
#box {
width: 100px;
height: 100px;
padding: 1ch;
box-sizing: border-box;
background-color: red;
border-radius: 5px;
color: white;
}
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<div id="box">Drag Me!</div>
</body>
</html>
Hopefully this solution is helpful to you!
The default behaviour will stop mouseMove and mouseUp from running, you can solve this by basically adding event.preventDefault() to the mousedown function
please ensure that you use the same parameter name passed in the mousedown function to trigger the preventDefault() if not it will not work , in the example below i passed event as the parameter to the mousedown function and then triggered preventDefault() by typing event.preventDefault()
let sliderImages = Array.from(document.getElementsByClassName('slidess'));
const sliderPos = sliderImages.forEach( function (slide, index) {
let mousePosStart, isDown = false;
slide.addEventListener('mousedown', mousedown)
slide.addEventListener('mousemove', mousemove)
slide.addEventListener('mouseup', mouseup)
function mousedown(event) {
if (isDown == false) {
mousePosStart = event.pageX - this.offsetLeft;
isDown = true;
event.preventDefault();
}
}
function mousemove(event) {
if (isDown == true) {
let mousePosMove = event.pageX - this.offsetLeft;
}
}
function mouseup(event) {
if (isDown === true) {
isDown = false;
let mousePosEnd = event.pageX - this.offsetLeft;
}
}
});
I am making a slider and I detect the position of the mouse to define click event. I create a $(document).on('mousemove') event and when I am on the position I want a click, I add a on('click') event, but in this case, the event it's called so many time, and not just one time.
Let's see this code. Here is a quick example : jsFiddle
var widthScreen = $(window).width();
$(document).on('mousemove', function(e) {
console.log(e.pageX);
if (e.pageX > (widthScreen - 120) && e.pageX < widthScreen) {
$('ul').addClass('right-show');
$('li').eq(2).on('click', function() {
console.log('too much click');
});
} else {
$('ul').removeClass('right-show');
}
});
How can I solve this issue ?
When ever you do the mousemove, it is checking the condition and attaching the click event. So the click event is attached many times. To avoid this, first remove the click event using off('click') and attach it. Here is the updated fiddle.
var widthScreen = $(window).width();
$(document).on('mousemove', function(e) {
console.log(e.pageX);
if (e.pageX > (widthScreen - 120) && e.pageX < widthScreen) {
$('ul').addClass('right-show');
$('li').eq(2).off('click').on('click', function() {
console.log('too much click');
});
} else {
$('ul').removeClass('right-show');
}
});
Remove the event attachment from mousemove handler, and create a flag to check, if the cursor is on correct position:
var widthScreen = $(window).width(),
onArea = false;
$(document).on('mousemove', function(e) {
if (e.pageX > (widthScreen - 120) && e.pageX < widthScreen) {
$('ul').addClass('right-show');
onArea = true;
} else {
$('ul').removeClass('right-show');
onArea = false;
}
});
$('li').eq(2).on('click', function(e) {
if (onArea) {
console.log('Not too much clicks.');
}
});
A live demo at jsFiddle.
Have a look at underscore.js throttle function:
_.throttle(function, wait, [options])
Creates and returns a new, throttled version of the passed function, that, when invoked repeatedly, will only actually call the original function at most once per every wait milliseconds. Useful for rate-limiting events that occur faster than you can keep up with
Use .one() instead of .on() Here
I have a couple of js queries.
Onclick isn't working on iPhones although its fine elsewhere.
JavaScript:
document.onclick = function(){newTarg(speedS)};
Any ideas on way round this, thinking maybe onchange but not sure how best to implement?
Also I am trying to get coordinates of the touch please help, so far code below.
JavaScript :
event = window.event;
xTarg = event.clientX;
yTarg = event.clientY;
Click events don't work on iOS use the touchstart, touchmove and touchend events to work out if the users tapped the screen.
JavaScript below:
var tap = true;
document.addEventListener('touchstart',function(e) {
tap = true;
});
document.addEventListener('touchmove',function(e) {
tap = false;
});
document.addEventListener('touchend',function(e) {
if(tap) {
//users tapped the screen
}
});
For user coords use the changedTouches object to see where on the page the user has tapped.
JavaScript:
var tap = true;
document.addEventListener('touchstart',function(e) {
tap = true;
});
document.addEventListener('touchmove',function(e) {
tap = false;
});
document.addEventListener('touchend',function(e) {
if(tap) {
var touch = e.changedTouches[0];
var pageX = touch.pageX;
var pageY = touch.pageY;
}
});
hope that helps
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';
}
}
}