Prevent touchstart event when scrolling/swiping on mobile devices - javascript

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().

Related

Scroll using Scroll-Bar Only

I am using three.js to allow users to create and edit a 3D model that involves using the scroll-wheel/two finger function, to zoom in and out. I want a second section of the page that is off the screen by default but the user can scroll down to see it. Preferably, this will be done only using the scroll bar, while the scroll-wheel can still be used.
For performance reasons, I'd prefer not to have to use something such as vue.js. Users provide data that remains on their computer that I'm using in both sections. This prevents me from just placing the data on another screen.
Overflow:hidden is out of the question because then I can not scroll to the bottom portion.
I tried using PreventDefault with several different EventListeners but none of them worked properly.
Below is the function that determines the size of the window and should include a function or the code to prevent scrolling.There aren't particular elements that shouldn't scroll, all of them shouldn't.
function onWindowResize() {
var viewWidth;
var viewHeight;
viewHeight=window.innerHeight-315;
//For Mobile
if(!UIactive && innerWidth < 640){
viewWidth= window.innerWidth;
//For Computer & Tablet
} else {
viewWidth= window.innerWidth -317;
if(window.innerHeight < 700){
viewHeight=window.innerHeight-52.67;
//Disable Scrollwheel
window.addEventListener('wheel',function(event){
//mouseController.wheel(event);
event.preventDefault();
}, false);
}
}
camera.aspect = (viewWidth) / (viewHeight);
camera.updateProjectionMatrix();
renderer.setSize(viewWidth, viewHeight);
UI.style.height= (viewHeight+'px');
}
Edit: I tried using the answer to a similar question. This did not achieve the desired result. I changed the code to be both window... and document... and a console.log statement included works but I can still scroll.
this.canvas.addEventListener('wheel',function(event){
mouseController.wheel(event);
return false;
}, false);
I then proceeded to try using preventDefault again and recieved the following error
Unable to preventDefault inside passive event listener due to target being treated as passive
Google Chrome docs say that,
With this intervention wheel/touchpad scrolling won't be blocked on document level wheel event listeners that do not need to call preventDefault() on wheel events.
Thus, you should apply the onmousewheel event on a specific div like so:
<div id="ScrollableDiv" style="height : 900px;background-color : red">
</div>
function stop(){
return false;
}
var div = document.getElementById('ScrollableDiv');
div.onmousewheel= stop;
Please refer this working fiddle.

Auto refresh a Div without scrolling to the top of Div

I have a script that refreshes a Div on my website every 20 seconds. The problem is, once it refreshes, it scrolls to the to of the Div. I want it to stay at the last position and not scroll to the top after a refresh. Could someone please look at this script and maybe point out what I'm doing wrong? Thanks in advance!
var time = new Date().getTime();
var refreshTime = 20*1000;
$(document).bind("blur focus focusin focusout load resize scroll unload click dblclick mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave change select submit keydown keypress keyup error hover change", function(e) {
time = new Date().getTime();
});
var lastScrollPos = 0;
$('#feed1').on('scroll', function() {
lastScrollPos = this.scrollTop;
});
function refresh() {
if(new Date().getTime() - time >= refreshTime)
$('#feed1').load(location.href="/dashboard" , function () {
$(this).scrollTop(lastScrollPos);
});
else
setTimeout(refresh, refreshTime);
}
setTimeout(refresh, refreshTime);
Why don't you use feed1 div only for loading your dashboard contents and handle its position using style.
#feed1 {
height: 150px;
overflow: auto;
}
Add other data outside feed1 div because load method will overwrite feed1's content.
See this example if you are looking for something similar otherwise you can modify this example so that other can understand your requirement/scenario.
If you do location.href="/dashboard", the browser will discard all the page's state (including scripting variables) and load "/dashboard" (assigning a value to location.href is identical to calling location.assign("/dashboard")).
The jQuery load function will probably not even require you to reposition the scroll offset, if you gave it chance to execute!
Try:
$('#feed1').load("/dashboard #feed1");
UPDATE:
It seems the HTTP request fired by jQuery's load mechanism is receiving a truncated response in your case (content-length: 0).
You would have to put the scroll position you want to keep into localStorage. Try:
var time = new Date().getTime();
var refreshTime = 20*1000;
$(document).bind("blur focus focusin focusout load resize scroll unload click dblclick mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave change select submit keydown keypress keyup error hover change", function(e) {
time = new Date().getTime();
});
var previousScrollPos = localStorage.getItem("lastScrollPos");
if(previousScrollPos)
{
$('#feed1').scrollTop(previousScrollPos);
localStorage.removeItem("lastScrollPos");
}
function refresh() {
if(new Date().getTime() - time >= refreshTime)
{
localStorage.setItem("lastScrollPos", $('#feed1').scrollTop());
location.reload();
}
}
setInterval(refresh, refreshTime);
I'm not 100% sure that you want to bind to the scroll event of #feed1 or just of body, I haven't seen your page. If anybody clicks "load more" on the news feed, those additional items will be hidden again since you're reloading the page. Not ideal at all.
Many users will hate having the page periodically reload, it's also an accessibility failure since this will interfere with screen reading software. It might be a simpler idea to just put a refresh newsfeed icon on the page, which just reloads the whole page, when the user wants to (instead of periodically).

Scroll the page when a canvas is touch dragged

I have an HTML5 canvas that users interact with by clicking (or tapping).
$(function() {
var canvas = $('#annotations');
canvas[0].addEventListener('mousedown', clickCanvas);
canvas[0].addEventListener('touchstart', clickCanvas);
});
function clickCanvas(e) {
markLocation(e);
drawCanvas();
e.preventDefault();
}
This works as expected. However, on mobile devices if you tap and drag this registers a click at the point where the tap started (this makes sense because it's hooked up to touchstart). The page does not scroll as it normally does when you touch-drag outside the canvas.
When dragging, I would like the tap to be ignored and the whole page scrolled instead.
I was able to resolve this by:
Removing e.preventDefault();
Hooking up canvas[0].onselectstart = function () { return false; } to prevent text being selected when the canvas is double-clicked (this was what e.preventDefault() did in the first place)
Replacing touchstart with touchend

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.

Detect whether scroll event was created by user

Is it possible to tell whether a scroll event was done by the browser or by the user? Specifically, when using the back button a browser may jump to the last known scroll position. If I bind to scroll event how can I tell whether this was caused by user or browser?
$(document).scroll( function(){
//who did this?!
});
I see three types of situations that cause scrolling in a browser.
The user performs some action. For example, uses mousewheel, arrow keys, page up/down keys, home/end keys, clicks the scrollbar or drags its thumb.
The browser scrolls automatically. For example, when using the back button in your browser it will jump to the last known scroll position automatically.
Javascript scrolls. For example, element.scrollTo(x,y).
Unfortunately, there is no direct way of telling that.
I would say if you can redesign your app so that it doesn't depend on this type of flow, go for that.
If not, a workaround I can think of is to keep track of user initiated scrolls and check that to see if the scroll was triggered by the browser or by the user.
Here's an example that I put together which does this pretty well (except for browsers where jQuery history has problems with).
You need to run this locally to be able to test it fully (jsFiddle/jsbin are not good fits as they iFrame the contents).
Here's the test cases that I validated:
Page loads - userScroll is false
Scroll using mouse/keyboard - userScroll becomes true
Click on the link to jump to page bottom - userScroll becomes false
Click Back/Forward - userScroll becomes false;
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<script src="http://code.jquery.com/jquery-1.6.1.min.js"></script>
<script type="text/javascript" src="https://raw.github.com/tkyk/jquery-history-plugin/master/jquery.history.js"></script>
</head>
<body>
<span> hello there </span><br/>
click here to go down
<br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/>
<br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/>
<br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/>
<br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/>
<br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/>
<br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/>
<br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/>
<a name="bottom"> just sitting </a>
</body>
<script type="text/javascript">
var userScroll = false;
function mouseEvent(e) {
userScroll = true;
}
$(function() {
// reset flag on back/forward
$.history.init(function(hash){
userScroll = false;
});
$(document).keydown(function(e) {
if(e.which == 33 // page up
|| e.which == 34 // page dn
|| e.which == 32 // spacebar
|| e.which == 38 // up
|| e.which == 40 // down
|| (e.ctrlKey && e.which == 36) // ctrl + home
|| (e.ctrlKey && e.which == 35) // ctrl + end
) {
userScroll = true;
}
});
// detect user scroll through mouse
// Mozilla/Webkit
if(window.addEventListener) {
document.addEventListener('DOMMouseScroll', mouseEvent, false);
}
//for IE/OPERA etc
document.onmousewheel = mouseEvent;
// to reset flag when named anchors are clicked
$('a[href*=#]').click(function() {
userScroll = false;
});
// detect browser/user scroll
$(document).scroll( function(){
console.log('Scroll initiated by ' + (userScroll == true ? "user" : "browser"));
});
});
</script>
</html>
Notes:
This doesn't track scrolling when the user drags the scrollbar with mouse. This can be added with some more code, which I left as an exercise for you.
event.keyCodes may vary by OS, so you may have to change that appropriately.
Hope this helps!
Rather than trying to catch all the user events, it's much easier to do the opposite and handle only the programmatic events - and ignore those.
For example, this kind of code would work:
// Element that needs to be scrolled
var myElement = document.getElementById('my-container');
// Flag to tell if the change was programmatic or by the user
var ignoreNextScrollEvent = false;
function setScrollTop(scrollTop) {
ignoreNextScrollEvent = true;
myElement.scrollTop = scrollTop
}
myElement.addEventListener('scroll', function() {
if (ignoreNextScrollEvent) {
// Ignore this event because it was done programmatically
ignoreNextScrollEvent = false;
return;
}
// Process user-initiated event here
});
Then when you call setScrollTop(), the scroll event will be ignored, while if the user scroll with the mouse, keyboard or any other way, the event will be processed.
As far as I know it is impossible (without any work) to tell whenever scroll event has been issued by "user" or by other means.
You could try (as others mentioned) catch mousewheel events, then probably trying to catch keydown event on any keys that can trigger scroll (arrows, space etc.) while checking what element is currently focused, since you for example can't scroll using arrow keys while typing in an input field.
In general that would be complex and messy script.
Depending on situation you're dealing with you could I guess "revert the logic", and instead of detecting user issued scroll events just hook in into any scrolls made programatically and treat any scroll events not made by your code as made by an user.
Like I said it depends on a situation, and what you're trying to achive.
Yes, it is 100% possible. I'm current using this in an application where IE is not a requirement - client facing only. When my Backbone app initiates an animation where scroll is changed - scroll occurs but does not trigger these event captures. This is tested in FF, Safari & Chrome latest.
$('html, body').bind('scroll mousedown wheel DOMMouseScroll mousewheel keyup', function(evt) {
// detect only user initiated, not by an .animate though
if (evt.type === 'DOMMouseScroll' || evt.type === 'keyup' || evt.type === 'mousewheel') {
// up
if (evt.originalEvent.detail < 0 || (evt.originalEvent.wheelDelta && evt.originalEvent.wheelDelta > 0)) {
// down.
} else if (evt.originalEvent.detail > 0 || (evt.originalEvent.wheelDelta && evt.originalEvent.wheelDelta < 0)) {
}
}
});
Try using the Mousewheel and DOMMouseScroll events instead. See http://www.quirksmode.org/dom/events/scroll.html
You can check the scroll position on ready. When you fire the on scroll event check to make sure the scroll position is different than it was when the page loaded. Lastly be sure to clear out the stored value once the page is scrolled.
$(function () {
var loadScrollTop = ($(document).scrollTop() > 0 ? $(document).scrollTop() : null);
$(document).scroll(function (e) {
if ( $(document).scrollTop() !== loadScrollTop) {
// scroll code here!
}
loadScrollTop = null;
});
});
Regarding to:
Specifically, when using the back button a browser may jump to the last known scroll position.
That fires very soon, after the page is rendered. You can just delay listenting to the scroll event by 1 second or so.
There is one more way to separate the user-created scroll: you can use the alternative event handlers, for example 'mousewheel', 'touchmove', 'keydown' with codes 38 and 40 for arrow scrolling, for scrolling with scroll bar - if 'scroll' event is fired simultaneously with 'mousedown' until 'mouseup' event.
Found this very useful. Here's a coffeescript version for those so inclined.
$ ->
S.userScroll = false
# reset flag on back/forward
if $.history?
$.history.init (hash) ->
S.userScroll = false
mouseEvent = (e)->
S.userScroll = true
$(document).keydown (e) ->
importantKey = (e.which == 33 or # page up
e.which == 34 or # page dn
e.which == 32 or # spacebar
e.which == 38 or # up
e.which == 40 or # down
(e.ctrlKey and e.which == 36) or # ctrl + home
(e.ctrlKey and e.which == 35) # ctrl + end
)
if importantKey
S.userScroll = true;
# Detect user scroll through mouse
# Mozilla/Webkit
if window.addEventListener
document.addEventListener('DOMMouseScroll', mouseEvent, false);
# for IE/OPERA etc
document.onmousewheel = mouseEvent;
if you're using JQuery than there's a better answer, apparently - i'm just trying it out myself.
see: Detect jquery event trigger by user or call by code
It might not help with your application, but I needed to fire an event on user scroll but not programatic scroll and posting incase it helps anyone else.
Listen to the wheel event instead of scroll,
It is triggered whenever a user uses the mouse wheel or tracker pad( which I feel is how most people scroll anyway) and isn't fired when you programatically scroll. I used it to differentiate between a user scroll action and scrolling functions.
https://developer.mozilla.org/en-US/docs/Web/API/Element/wheel_event
element.addEventListener('wheel', (event) => {
//do user scroll stuff here
})
One caveat is that wheel doesn't fire on scroll on mobile, so I checked whether the device was mobile and used similar functions
if(this.mobile){
element.addEventListener('scroll', (event) => {
//do mobile scroll stuff here
})
}

Categories

Resources