Mousepad firing too many "wheel" events in JavaScript - javascript

I'm trying to detect "wheel" events on a web page to intercept these and implement a page-by-page scroll instead.
This works fine with a mouse - using the wheel seems to trigger a single "wheel" event, which I'm able to intercept.
I have an issue with mousepad however, which seems to fire multiple successive "wheel" events. I have tried throttling my custom scroll function using underscoreJS and disabling trailing end, but somehow the subsequent events are still fired..
wheelHandlerThrottled: _.throttle(function(e, pageNum) {
// My scrolling code
}, 500, {leading: true, trailing: false})
When on page 1 and scrolling down with mousepad, I'll get the following behavior:
Scroll to page 2
500 ms pause
Scroll to page 3
500 ms pause
Scroll to page 4
Logging events in the console shows me that 3 "wheel" events are fired and processed.. so it's like my throttling is not working, but instead a pause is inserted between every event.

Throttle seems to just pile on the scroll events.
I would do it with something like this jsfiddle
Essentialy a event listener for mousewheel and when its triggered there is a timeout for x miliseconds until it can be triggered again.
let canScroll = true;
let marginTop = 10;
const element = $('#custom');
window.addEventListener('mousewheel', (event) => {
if (canScroll) {
if (event.deltaY > 0) {
marginTop += 10;
} else {
marginTop -= 10;
}
element.css('margin-top', marginTop + 'px');
canScroll = false;
setTimeout(() => {
canScroll = true;
}, 1000);
}
});

Related

Is there a way to manually add delay to all user input DOM events?

For a research experiment I am trying to delay the user interface (create lag) on mobile browsers, as I am researching the effects of UI latency in webapps. For example, if a user scrolls the scroll action only happens (e.g.) 50ms later.
I've tried window.addEventListener(), and then window.dispatchEvent() after a certain delay with setTimeout(). Howver, in the case of scrolling, this did not scroll the page after dispatching the event manually. Scrolling with window.scrollBy() does work, but it fires its own event.
window.addEventListener('wheel', event => {
console.log(event)
if (event.cancelable) {
event.preventDefault()
event.stopImmediatePropagation()
setTimeout(() => {
let newEvent = new WheelEvent('wheel', {
deltaX: event.deltaX,
deltaY: event.deltaY,
deltaZ: event.deltaZ,
cancelable: false,
})
window.dispatchEvent(newEvent)
// window.scrollBy({ top: 20 })
}, DELAY)
}
}, {
capture: true,
passive: false,
})
This works for wheel events, but not for touch events.
If there a way to generalize this behaviour for all MouseEvents?
Ideally I would like to process all DOM MouseEvent's, like some sort of middleware.

Prevent touchstart event when scrolling/swiping on mobile devices

I have a site that needs to work on mobile devices. If I touch a link while attempting to scroll down the page, it triggers the touchstart event (in most cases loading a new window, but in the case of the header, navigating through the menu). I want to be able to scroll without touchstart events being triggered. How can I accomplish this?
I've figured out a solution that works for most clickable items on the page:
$(document).bind("touchstart", function (e) {
touchStartPos = $(window).scrollTop();
}).bind("touchend", function (e) {
var distance = touchStartPos - $(window).scrollTop();
if (distance > 20 || distance < -20) {
e.preventDefault;
}
});
A few items on my page seem to not get bound, but you can just specifically bind each item as needed in addition to doing a general $(document).bind().

Click triggers mousemove in Chrome [duplicate]

I don't know whether it is only Chrome problem (can't check now), however let's try the following piece of code, where we bind two events to some element:
$("div").on({
mousemove: function(e) {
console.log("move");
},
click: function(e) {
console.log("click");
}
});
If we try to click the element, we'll find that for some reason mousemove event fires immediately after click, so in console we have:
>> ...
>> click
>> move
DEMO: http://jsfiddle.net/gKqVt/
Note, that mousedown and mouseup events work by the same scenario.
I saw many questions on SO about the same problem, but none (in my search) gave the straightforward idea what to do in order to fire the click event only.
Mousemove appears to be binded to every mouse action there is in Chrome, so store the mouse position every time the mouse "moves" and check it against the previous mouse position to validate that it has indeed "moved"..
var currentPos=[];
$("div").on({
mousemove: function(e) {
if (e.pageX!==currentPos[0] && e.pageY !==currentPos[1]){
currentPos=[e.pageX,e.pageY];
this.innerHTML = "Event: " + e.type;
console.log("move");
}
},
click: function(e) {
this.innerHTML = "Event: " + e.type;
console.log("click");
}
});
Demo | Source
This appears to be a bug in Chrome that was first reported back in November, and remains open.
Chromium Issue 161464
If you are targeting Chrome specifically then it may be worth comparing the event timestamps to get around it (using some minimum delta time as #ExplosionPills suggested. But if you're looking for general behavior it seems that you're better off treating them as separate events, because in every browser but chrome (and maybe Safari? the bug is labeled as webkit-core) they will in fact be separate events.
This behavior is odd, and it doesn't seem to occur universally (happens in Chrome/IE for me, but not FFX). I think you haven't gotten a straight answer because there isn't one really.
It's possible that the mouse is moved very slightly by the click action, but that's probably not it. Could just be a browser quirk. These don't even seem to be the same event since stopImmediatePropagation in click doesn't stop mousemove from firing. If you focus the element and hit a keyboard button, it will actually trigger click and only click.
Since this is so quirky, it seems like the only way to deal with it is times. As much of a kludge as this is, I do notice that click happens one millisecond before mousemove, so you could get close by comparing the click timestamp + 2 (or 10):
mousemove: function(e) {
if ($(this).data('lastClick') + 10 < e.timeStamp) {
http://jsfiddle.net/gKqVt/3/
This is very specific, though. You should consider not having behavior that occurs immediately on mousemove since it's so frequent.
Why don't just check that did the mouse really move or not like below:
function onMouseDown (e) {
mouseDown = { x: e.clientX, y: e.clientY };
console.log("click");
}
function onMouseMove (e) {
//To check that did mouse really move or not
if ( e.clientX !== mouseDown.x || e.clientY !== mouseDown.y) {
console.log("move");
}
}
FIDDLE DEMO
(I think it's will still correct in all browsers)
var a,b,c,d;
$(".prd img").on({
mousedown: function(e){
a= e.clientX, b= e.clientY;
},
mouseup: function(e){
c= e.clientX, d= e.clientY;
if(a==c&&b==d){
console.log('clicked');
}
}
});
Try this. This one work correct.
I noticed this behavior when I needed to differenciate between mousedown and mouseup without dragging between the two and mousedown and mouseup with dragging between them, the solution that I used is as follows:
var div = $('#clickablediv');
var mouseDown = false;
var isDragging = 0;
div.mousedown(function () {
isDragging = false;
mouseDown = true;
}).mousemove(function () {
if (mouseDown) isDragging++;
}).mouseup(function () {
mouseDown = false;
var wasDragging = isDragging;
isDragging = 0;
if (!wasDragging || wasDragging<=1) {
console.log('there was no dragging');
}
});
when I tried it, I noticed that periodacaly a simple click makes "isDragging" equal to 3 but not very frequently
I added the following to my mouseMove(event) function:
function mouseMove(event)
{
if ((event.movementX == 0) && (event.movementY == 0)) return;
Not clear why it triggers when there is no movement, but this worked for me. Had the issue in Chrome 102.0.5005.61 at least. It did not happen a few years ago.

JavaScript on iOS: preventDefault on touchstart without disabling scrolling

I am working with JavaScript and jQuery in an UIWevView on iOS.
I'v added some javascript event handler that allow me to capture a touch-and-hold event to show a message when someone taps an img for some time:
$(document).ready(function() {
var timeoutId = 0;
var messageAppeared = false;
$('img').on('touchstart', function(event) {
event.preventDefault();
timeoutId = setTimeout(function() {
/* Show message ... */
messageAppeared = true;
}, 1000);
}).on('touchend touchcancel', function(event) {
if (messageAppeared) {
event.preventDefault();
} else {
clearTimeout(timeoutId);
}
messageAppeared = false;
});
});
This works well to show the message. I added the two "event.preventDefault();" lines to stop imgs inside links to trigger the link.
The problem is: This also seems to prevent drag events to scroll the page from happen normally, so that the user wouldn't be able to scroll when his swipe happens to begin on an img.
How could I disable the default link action without interfering with scrolling?
You put me on the right track Stefan, having me think the other way around. For anyone still scratching their head over this, here's my solution.
I was trying to allow visitors to scroll through images horizontally, without breaking vertical scrolling. But I was executing custom functionality and waiting for a vertical scroll to happen. Instead, we should allow regular behavior first and wait for a specific gesture to happen like Stefan did.
For example:
$("img").on("touchstart", function(e) {
var touchStart = touchEnd = e.originalEvent.touches[0].pageX;
var touchExceeded = false;
$(this).on("touchmove", function(e) {
touchEnd = e.originalEvent.touches[0].pageX;
if(touchExceeded || touchStart - touchEnd > 50 || touchEnd - touchStart > 50) {
e.preventDefault();
touchExceeded = true;
// Execute your custom function.
}
});
$(this).on("touchend", function(e) {
$(this).off("touchmove touchend");
});
});
So basically we allow default behavior until the horizontal movement exceeds 50 pixels.
The touchExceeded variable makes sure our function still runs if we re-enter the initial < 50 pixel area.
(Note this is example code, e.originalEvent.touches[0].pageX is NOT cross browser compatible.)
Sometimes you have to ask a question on stack overflow to find the answer yourself. There is indeed a solution to my problem, and it's as follows:
$(document).ready(function() {
var timeoutId = 0;
$('img').on('touchstart', function(event) {
var imgElement = this;
timeoutId = setTimeout(function() {
$(imgElement).one('click', function(event) {
event.preventDefault();
});
/* Show message ... */
}, 1000);
}).on('touchend touchcancel', function(event) {
clearTimeout(timeoutId);
});
});
Explanation
No preventDefault() in the touch event handlers. This brings back scrolling behavior (of course).
Handle a normal click event once if the message appeared, and prevent it's default action.
You could look at a gesture library like hammer.js which covers all of the main gesture events across devices.

JQuery Distinction between quick Click event and a prolonged MouseDown

I'm trying to create a scrolling button that reacts differently to a quick click event than it does to a prolonged MouseDown (click and hold). The quick click event will scroll a specific number of pixels while click and hold will slowly scroll the pane until mouse up where it will stop.
This is what I have currently:
var mdown;
$('.next').bind('mousedown', function(event) {
mdown = event.timeStamp;
moving = setInterval(function(){
$('#main').scrollLeft($('#main').scrollLeft() + 5);
}, 1);
});
$('.next').bind('mouseup', function(event) {
clearInterval(moving);
if ((event.timeStamp - mdown) < 100)
$('#main').animate({ scrollLeft : '+=800'}, 500);
});
Is there another way of doing this without comparing event timestamps? Is a click event treated any differently than mousedown/mouseup? Thanks!
Check this plugin(It defines an event to handle long clicks):
https://github.com/pisi/Longclick

Categories

Resources