Javascript stop scrolling on touchmove after scrolling has already started - javascript

I have a simple example where a user starts to scroll on a touch screen, and then after one second, I want to disable scrolling. I thought event.preventDefault() would stop the scrolling but it doesn't seem to work after scrolling has already started
Here is an example: https://jsfiddle.net/7s5m8c6L/30/
let allowScroll=true;
function TS(e){//touchstart handler
setTimeout(function(){
allowScroll=false;
},1000)
}
function TM(e){//touchmove handler
if(!allowScroll){
e.preventDefault();
}
}
In this example, you can start scrolling, and after a second, I want the scrolling to stop, but it does not. I know there are ways that I can get this to work with CSS (adding overflow:hidden), but I would particularly like to know why preventDefault doesn't work.

If you are using chrome, there is a hint in the console:
[Intervention] Ignored attempt to cancel a touchmove event with cancelable=false, for example because scrolling is in progress and cannot be interrupted.
The problem is exactly that Event.cancelable. Unfortunately for you this property is read-only and it is not safe to call preventDefault for a not cancelable event. If you print e.cancelable in the TM function you can observe that throughout the scrolling e.cancelable is false.

Related

How to prevent touchend event after dragend?

I'm working on a mobile site and struggling with events firing when I don't want them to.
For the sake of simplicity, it's written something like this (in jQuery):
el.on('touchend', function(ev) {
ev.preventDefault();
// fire an ajax call
};
However, sometimes a user would hit the item when scrolling the page, causing the ajax request to fire (thus changing the page state).
I couldn't think of a way around it (ev.stopPropagation() didn't work) , so I decided watch for dragstart and dragend events.
el.on('dragstart', function() {
el.off('touchend');
});
el.on('dragend', function(ev) {
ev.stopPropagation(); // <-- seems to do nothing
// add back the event above (the function is set to a var)
});
If I alert inside the touchend callback, I get confirmation that the touchend event did in fact fire after I stopped dragging.
Does anyone have any idea how to prevent any other events from firing? I'm hoping I'm just being blind and missing something obvious.
You can't stop an event from firing, you can only prevent the default behavior for that event from happening.
If you're worried about the state of your page changing before the touchend event fires, you should just change your function to check for and then account for the state change.
I think in a case like this you should use event.stopImmediatePropagation();

mobile Safari vertical scrolling - how to detect when the window has stopped moving in Javascript

Is there a js method to detect when a vertical flick on a long iOS safari page has stopped moving, such as an equivalent to the pseudo:
window.element.momentumScroll == false
This is to detect if the decelerating content is still moving or the scroll event has finished.
Any and all clues gratefully received.
ADDENDUM I have not implemented any external libraries in my code (no jQuery etc) and need to find a native js listener/method to tell me when the flick scroll has ended.
doc.addeventlistener("scroll", function(e){setvariable to 1}, false)
doc.addeventlistener("noscroll", function(e){setvariable to 0}, false)
Method:
startTop = window.pageYOffset on touchStart
currTop = window.pageYOffset on touchEnd
deltaTop = startTop - currTop
deltaTop == 0 means no momentum scrolling occurred during another event.
I'm not sure if I understood the question correctly. I believe u are trying to achieve something like loading new content when the page reaches its bottom? (forgive me for assuming)
I think you are looking for some javascript gesture library, if your event is based on touches.
There are Mootools library on this
Powertools: http://cpojer.net/PowerTools/#!
Drag.Flick: http://mootools.net/forge/p/drag_flick
There should be equal implementation in other framework as well. (jQuery: http://jgestures.codeplex.com/)
Possible solution is to look for an event that can return the current position of touches that exceeds document.body.clientHeight (read: not cross platform) .
Hope I manage to point to the right way.
just do a setTimeout in the touchend event. The timeout will fire once the touchend has stopped working. Timers get paused during touch event. On ios set timeout will fire once the page has stopped scrolling and there is no longer momentum.
body.addeventlistener("ontouchend", function(e){
setTimeout(function(){
alert("done moving")
},0);
}, false);
or
$('body').on('touchend.scroll', function () {
setTimeout(function(){
alert("done moving")
},0);
});
Note that Android will fire the event as soon as you let your finger go. Timers dont seem to be paused.

auto scroll: stop jumps back to top of page

I have a page in which the user clicks one link to start scrolling down the page automatically for ease in reading. There is another link the user clicks to stop the scrolling. The former works perfectly, but the latter makes the page jump back to the top when clicked instead of stopping the scrolling at the that place on the page. Any ideas?
function pageScroll() {
window.scrollBy(0,1); // horizontal and vertical scroll increments
scrolldelay = setTimeout('pageScroll()',50); // scrolls every 100 milliseconds
}
function stopScroll() {
clearTimeout(scrolldelay);
}
I tried to add return false; to the second function from something I read on another post, but it didn't help. I don't fully understand the use of return anyhow. Thanks for any help.
I assume that you're doing something like this:
start
stop
The quickest fix is to return false from the onclick event handlers, like this:
start
stop
The idea is to stop the browser from doing the default action of the event (in this case, going to #, which scrolls to the top of the page). Nowadays, the more modern way is to bind an event handler function, then use e.preventDefault() in it, but return false; still works for old-style event attributes.

$(window).scrollTop tied to $(window).scroll() event acting oddly

I'm trying to trigger a function when the window is scrolled more than a certain number of pixels.
Here's my code:
$(window).scroll(function(){
if( $(this).scrollTop() >= 100 ) {
someFunction();
} else {
someOtherFunction();
}
});
It kinda works, but there's either a delay of around 2-4 seconds after scrolling before the function(s) are fired or else the functions aren't triggered at all.
Tried it out in Safari / Chrome. Don't know if that helps or not!
The code looks fine and works for me.
As Wolfram says, it's rarely a good idea to attach handlers directly to the scroll event, as this fires a lot and can bring the user's system to a crawl.
I'd recommend using Ben Alman's jquery throttle/debounce plugin.
It works using jQuery 1.6.1 + mousewheel / scrollbar in Chrome15/Safari5.1/FF7 on OSX. What are you doing in those two functions? For testing, I put a simple alert() in someFunction and nothing in someOtherFunction.
Remember that one of those functions is executed every time the scroll-event fires unless you stop it once it was called... e.g. someFunction is called a lot after you scrolled below the 100px line.
John Resig: It's a very, very, bad idea to attach handlers to the window scroll event.
If you're scolling by holding in the click-button instead of using the scroll wheel, I believe the event won't fire until you release the click-button.
Have you considered running a loop that checks the scrollTop instead?
EDIT:
I just check an old project of mine using window scroll event, and it runs perfect with the same event.
I asume you have this script of yours wrapped inside:
$(function() {
// code
});

How to distinguish scrolling by mouse from scrolling programmatically in JavaScript?

I am scrolling an overflowing DIV's content by changing the scrollLeft property in Javascript:
setInterval(function(){
$('#scrollbox').scrollLeft($('#scrollbox').scrollLeft()+1);
}, 50);
However, I want to stop this as soon as the user scrolls the content themselves, using the mouse. I tried to detect this using the scroll event
$('#scrollbox').scroll(function(){...});
however, my automatic scrolling above also triggers that event. How can I distinguish this and only react to user-initiated scrolling? (or: how can I stop the above code from firing a scroll event? That would also do the trick)
You could use the .hover(): function to stop the scrolling when the mouse is over the scrollbox element:
http://jsfiddle.net/bGHAH/1/
setInterval(function(){
if(!mouseover)
{
$('#scrollbox').scrollLeft($('#scrollbox').scrollLeft()+1);
}
}, 50);
var mouseover = false;
$('#scrollbox').hover(function(){
mouseover = true;
},function(){
mouseover = false;
});
Edit
Based on your comments I managed to find a jquery plugin from the following site: special scroll events for jquery.
This plugin contains an event which attempts to determine whether scrolling has stopped based on the period of time that has elapsed between the last scroll step and the time the check was made.
To get this to work I needed to slow your interval to just over the latency used by the plugin which worked out to be 310 milliseconds. Doing this meant I had to increase the scroll step to keep it visibly moving.
Here is the link:
http://jsfiddle.net/EWACn/1/
and here is the code:
var stopAutoScroll = false;
$(document).ready(function(){
setInterval(function(){
if(!stopAutoScroll)
{
$('#status').html('scrolling');
$('#scrollbox').scrollLeft($('#scrollbox').scrollLeft()+10);
}else{
$('#status').html('not scrolling');
}
}, 310);
$('#scrollbox').bind('scrollstart', function(e){
stopAutoScroll = true;
});
$('#scrollbox').bind('scrollstop', function(e){
stopAutoScroll = false;
});
});
Hope this helps.
For FF (Mozilla):
document.addEventListener('DOMMouseScroll', handler, false);
For IE, Opera and Chrome:
document.onmousewheel = handler;
Another option is to have an external flag that you can set prior to the programmatic scrolling, and then reset afterwords. If the scroll event is fired and this flag isn't set you know that the user is responsible and can act accordingly.
Unfortunately while this is browser independent and easy to read it could lead you to believe that some user scrolls are programmatic ones. However I would think the occurrences of this is small and may be worth it depending on the app you are writing.
Try wheel event, for most modern browsers
The wheel event is fired when a wheel button of a pointing device (usually a mouse) is rotated.

Categories

Resources