I am working on some javascript UI, and using a lot of touch events like 'touchend' for improved response on touch devices. However, there are some logical issues which are bugging me ...
I have seen that many developers mingle 'touchend' and 'click' in the same event. In many cases it will not hurt, but essentially the function would fire twice on touch devices:
button.on('click touchend', function(event) {
// this fires twice on touch devices
});
It has been suggested that one could detect touch capability, and set the event appropriately for example:
var myEvent = ('ontouchstart' in document.documentElement) ? 'touchend' : 'click';
button.on(myEvent, function(event) {
// this fires only once regardless of device
});
The problem with the above, is that it will break on devices that support both touch and mouse. If the user is currently using mouse on a dual-input device, the 'click' will not fire because only 'touchend' is assigned to the button.
Another solution is to detect the device (e.g. "iOS") and assign an event based on that:
Click event called twice on touchend in iPad.
Of course, the solution in the link above is only for iOS (not Android or other devices), and seems more like a "hack" to solve something quite elementary.
Another solution would be to detect mouse-motion, and combine it with touch-capability to figure out if the user is on mouse or touch. Problem of course being that the user might not be moving the mouse from when you want to detect it ...
The most reliable solution I can think of, is to use a simple debounce function to simply make sure the function only triggers once within a short interval (for example 100ms):
button.on('click touchend', $.debounce(100, function(event) {
// this fires only once on all devices
}));
Am I missing something, or does anyone have any better suggestions?
Edit: I found this link after my post, which suggests a similar solution as the above:
How to bind 'touchstart' and 'click' events but not respond to both?
After a day of research, I figured the best solution is to just stick to click and use https://github.com/ftlabs/fastclick to remove the touch delay. I am not 100% sure this is as efficient as touchend, but not far from at least.
I did figure out a way to disable triggering events twice on touch by using stopPropagation and preventDefault, but this is dodgy as it could interfere with other touch gestures depending on the element where it is applied:
button.on('touchend click', function(event) {
event.stopPropagation();
event.preventDefault();
// this fires once on all devices
});
I was in fact looking for a solution to combine touchstart on some UI elements, but I can't see how that can be combined with click other than the solution above.
This question is answered but maybe needs to be updated.
According to a notice from Google, there will be no 300-350ms delay any more if we include the line below in the <head> element.
<meta name="viewport" content="width=device-width">
That's it! And there will be no difference between click and touch event anymore!
Yes disabling double-tap zoom (and hence the click delay) is usually the best option. And we finally have good advice for doing this that will soon work on all browsers.
If, for some reason, you don't want to do that. You can also use UIEvent.sourceCapabilities.firesTouchEvents to explicitly ignore the redundant click. The polyfill for this does something similar to your debouncing code.
Hello you can implement the following way.
function eventHandler(event, selector) {
event.stopPropagation(); // Stop event bubbling.
event.preventDefault(); // Prevent default behaviour
if (event.type === 'touchend') selector.off('click'); // If event type was touch turn off clicks to prevent phantom clicks.
}
// Implement
$('.class').on('touchend click', function(event) {
eventHandler(event, $(this)); // Handle the event.
// Do somethings...
});
Your debounce function will delay handling of every click for 100 ms:
button.on('click touchend', $.debounce(100, function(event) {
// this is delayed a minimum of 100 ms
}));
Instead, I created a cancelDuplicates function that fires right away, but any subsequent calls within 10 ms will be cancelled:
function cancelDuplicates(fn, threshhold, scope) {
if (typeof threshhold !== 'number') threshhold = 10;
var last = 0;
return function () {
var now = +new Date;
if (now >= last + threshhold) {
last = now;
fn.apply(scope || this, arguments);
}
};
}
Usage:
button.on('click touchend', cancelDuplicates(function(event) {
// This fires right away, and calls within 10 ms after are cancelled.
}));
For me using 'onclick' in the html element itself, worked for both touch and click.
<div onclick="cardClicked(this);">Click or Touch Me</div>
Related
I have a mobile web app, which uses a lot of click event handlers on buttons, etc. All of this works fine if the user really "clicks" (i.e. "touchdown-touchup") the button. However if the user does a short swipe, then the click event does not fire. This causes a lot of complaints from my users that the app doesn't register clicks/taps and that other apps work correctly.
Of course, I can get coordinates of the touch in ontouchstart and ontouchend and compute the distance - but I need to also know whether that distance is under the maximum that the browser would treat as 'click'. I do not want to switch to using touchstart/touchend events instead of click.
I used to use fastclick.js library for handling clicks/taps in the past, but now use native 'click' events with touch-action: manipulation. Is there any way of specify/controlling the maximum movement of the finger on the button that still registers as a 'click'?
Update based on comments. The application is very large and there are hundreds if not thousands of event handler assignments throughout it (the app has been developed over the last 8 years). Changing all of these is not practical, therefore I'm looking for a solution that would allow me to either set the threshold once globally or solve the problem with a global-like touchstart/touchend handlers.
I thought this was an interesting problem so I took a shot at solving it for you. In a way it's somewhat similar to the problem of preventing a click event when a dblclick happens.
Using a distance threshold for a "short swipe" seems, to me at least, problematic in that the threshold distance might be system dependent. Instead of that I decided to trigger on if the "click" event actually happens. I used mousedown as a simulated touchstart and mouseup as a simulated touchend. mouseup always happens before click so it is similar to touchend in that respect.
Normally if you "click" (mousedown) on an element and then move your mouse pointer off the element, the click event does not happen. This is much like the situation you describe as being a "short swipe". After a certain distance the click event just doesn't happen. The code below will send a click event for the button even if you mousedown on it, move the pointer off it and then mouseup. I believe that this would solve the problem if you used it for touchstart and touchend instead
// The pre-exisiting click handler
function handleClick(ev) {
console.log('button clicked. do work.');
}
document.getElementById('theButton').addEventListener('click', handleClick);
// our global "touch" handlers
var touchHandler = {
curPending: null,
curElem: null,
handleTouch: function handleTouch(ev) {
switch (ev.type) {
case 'mousedown':
// capture the target that the click is being initiated on
touchHandler.curElem = ev.target;
// add an extra click handler so we know if the click event happens
ev.target.addEventListener('click', touchHandler.specialClick);
break;
case 'mouseup':
// start a pending click timer in case the click event doesn't happen
touchHandler.curPending = setTimeout(touchHandler.pendingClick, 1);
break;
}
},
specialClick: function(ev) {
// the click event happened
// clear our extra handler
touchHandler.curElem.removeEventListener('click', touchHandler.specialClick);
// make sure we don't send an extra click event
clearTimeout(touchHandler.curPending);
},
pendingClick: function() {
// we never heard the click event
// clear our extra handler
touchHandler.curElem.removeEventListener('click', touchHandler.specialClick);
// trigger a click event on the element that started it all
touchHandler.curElem.click();
}
};
// using "mousedown" as "touchstart" and "mouseup" as "touchend"
document.addEventListener('mouseup', touchHandler.handleTouch);
document.addEventListener('mousedown', touchHandler.handleTouch);
<p>I work when clicked normally but I also work when
mousedown, drag pointer off me, mouseup</p>
<button id="theButton">Click Me</button>
I have an issue concerning the keyboards events in JS.
First of all, please do not answer me to use jQuery methods, I know most of it (bind/unbind, on/off, one...) but I work with an internal framework that have to work without jQuery, even if jQuery is used on most of our projects.
So, I have a module, in fact a swipe tool based on Swipe.js and extended to work on web and mobile environments (compatibility needed for IE 7+, WebKit (Chrome & Safari), Moz, Opera and IE10 / Windows Phone)
In do not have any problem with mouse/touch events, the binding and unbinding methods inspired from the mobile HTML5 BP seems to work very well with a small correction for the detachEvents method.
And then I would to implement a keyboard control feature based on 'keydown' events.
(BTW, I am not sure to make a good difference between keydon and keypress events, except the keypressEvent.preventDefault() do not prevent the small scroll effect, so I use keydown.)
As it is possible to add many Swipes on the same page, I start to listen the keydown events only when any Swipe is focused (Note that I add a "tabindex" attribute to allow the element to get focused).
<div id="swipe1" class="swipe" tabindex='0'>
<ul>
[...]
</ul>
</div>
Then when the Swipe handle a 'touchstart' / 'click' / ' MSPointerDown' event,
I focus it :
onTouchStart: function(e) {
this.container.focus(); // Refers to the div#swipe1.swipe element
[...]
return false;
}
onFocus: function (e) {
if (this.activateKeyboardControls) { // Keyboard control is optional
this.addListener(document, 'keydown', this, true);
}
}
onBlur: function (e) {
if (this.activateKeyboardControls) { // Keyboard control is optional
this.removeListener(document, 'keydown', this, true);
}
}
But unfortunately, the removeListener does not work.
I mean, when the element loses the focus (blur event fired), it still handle the keydown events...
Is it because it is binded on the document object ?
I have read some solutions working with some booleans but I am looking for a cleaner way the manage it.
This is annoying, because when I give the focus to many Swipes, each of them is swiping when I press the keyboard.
I'm not sure of the reason why my answer has been deleted - more than 2 weeks after posting - but anyway, this is how I solved it :
It comes from the 'type' parameter of the addEventListener / attachEvent method, the first of one so...
I bind it on the object instead of on the window, and without bubbling.
var target = e.target || e.srcElement;
if (this.activateKeyboardControls) {
this.addListener(target, 'keydown', this, false);
}
a need to speed up links with onClick attr in Phonegap app.
I would like to use Fast buttons plugin, that i found here:
https://developers.google.com/mobile/articles/fast_buttons
But i dont know, how to right use this plugin should i add this after pageinit or where?
Maybe is it quite silly question, but if i tried to find some examples, with no luck.
Could You add somebody add put here some example, how solve this problem?
Many thanks.
The touchstart (or touchend) event works great if you know the user won't be scrolling. That's actually the reason click events take so long to resolve on mobile devices, the device is waiting to see if the user is scrolling or clicking.
This will perform quite fast as there is no delay for dispatching this event:
$('#myButton').on('touchstart', function () {
//run click code now
});
You can also use jQuery Mobile's vclick event which attempts to use the native touch events but it's main problem is that you can dispatch multiple events using vclick so you should set a timeout to only allow one click at a time, for example:
var clickOk = true;
$('#myButton').on('vclick', function () {
if (clickOk === true) {
clickOk = false;
setTimeout(function () {
clickOk = true;
}, 350);
//run click code now
}
return false;
});
This will allow the event handler to run only once per 350ms which will take care of the multiple events being dispatched since the second event will be ignored.
I would set these event handlers up in a delegated event handler that runs when a pseudo-page gets initialized:
$(document).on('pageinit', '.ui-page', function () {
//bind "fast-click" event handlers now, use "$(this).find(...)" to only bind to elements of the current pseudo-page
});
Jiri If it's not too late I had to do the same thing for my app and needed to pass parameters to the function. I did it by placing the parameters in the id of the button (separarted by underscores) and using this function which grabs the id from every clicked button with a classname of "clickbutton" and splits it into the individual parameters.
$('.clickbutton').live('click', function(event) {
event.preventDefault();
var id = $(this).attr('id');
var parts = $(this).attr('id').split("_");
var item = parts[0];
var button = parts[1];
var type = parts[2];
console.log(item+button+type);
getItemCondition(item,type);
return false;
});
Still having issues with unresponsiveness from JQM click event though!
What about fastclick ?
FastClick is a simple, easy-to-use library for eliminating the 300ms delay between a physical tap and the firing of a click event on mobile browsers. The aim is to make your application feel less laggy and more responsive while avoiding any interference with your current logic.
I've built a webapp, and for a little bit of polish, I wanted to add mousedown and mouseup handlers to swap out images (in this case, to make a button look like it's being pressed).
my code is something like this:
window.onload = function() {
//preload mouse down image here via Image()
$("#button_img").mousedown(function(){$("#button_img").attr("src","button_on.png");});
$("#button_img").mouseup(function(){$("#button_img").attr("src","button_off.png")});
}
This works swimmingly on the desktop, but on mobile (testing in iOS Safari), the mousedown and mouseup events happen at the same time, so effectively nothing happens.
I tried to use the vmousedown and vmouseup events in jQueryMobile, however this code:
//include jquerymobile.js and jquerymobile.css
window.onload = function() {
//preload mouse down image here via Image()
$("#button_img").vmousedown(function(){$("#button_img").attr("src","button_on.png");});
$("#button_img").vmouseup(function(){$("#button_img").attr("src","button_off.png")});
}
Just gave me the errors that vmousedown and vmouseup don't exist. Also, jQueryMobile overrides the CSS I've already written for the page.
So is there a way to get vmousedown and vmouseup to work, and to do so without jQuery Mobile's CSS?
You're looking for touchstart and touchend. They are the events that vmousedown and vmouseup attempt to mimic.
Here's an example:
window.onload = function() {
//preload mouse down image here via Image()
$("#button_img").bind('touchstart', function(){
$("#button_img").attr("src","button_on.png");
}).bind('touchend', function(){
$("#button_img").attr("src","button_off.png");
});
}
This will work without any framework on any device that supports touch events. You could use something like Modernizr to do this test and if the device does not support touch events, bind to the regular desktop events.
When you use touchstart/touchend/touchmove you get some interesting information, for instance how many touches are occurring at once, so you can detect if the user is scrolling or attempting to zoom.
UPDATE
Since the event object inside an event handler differs for touch events and mouse events, if you want to know the coordinates of the event either way, you can do something like this (the example below assumes Modernizr has been loaded):
//determine which events to use
var startEventType = 'mousedown',
endEventType = 'mouseup';
if (Modernizr.touch === true) {
startEventType = 'touchstart';
endEventType = 'touchend';
}
//bind to determined event(s)
$("#button_img").bind(startEventType, function(event) {
//determine where to look for pageX by the event type
var pageX = (startEventType === 'mousedown')
? event.pageX
: event.originalEvent.touches[0].pageX;
...
})...
UPDATE
I was looking this over and it seems like you don't need to detect the event type before binding the event handler:
//bind to determined event(s)
$("#button_img").bind('mousedown touchstart', function(event) {
//determine where to look for pageX by the event type
var pageX = (event.type.toLowerCase() === 'mousedown')
? event.pageX
: event.originalEvent.touches[0].pageX;
...
})...
If you are worried about receiving both events in quick succession you could use a timeout to throttle the event handler:
//create timer
var timer = null;
//bind to determined event(s)
$("#button_img").bind('mousedown touchstart', function(event) {
//clear timer
clearTimeout(timer);
//set timer
timer = setTimeout(function () {
//determine where to look for pageX by the event type
var pageX = (event.type.toLowerCase() === 'mousedown')
? event.pageX
: event.originalEvent.touches[0].pageX;
...
}, 50);
})...
Note: You can force mousedown and touchstart events in quick succession with developer tools but I'm not sure about the real world use case here.
Have you considered styling your buttons using CSS instead? the :active state will be triggered when a user is clicking/touching the element. Here is an example:
/* Default state */
#button_img {
background-image: url('button_off.png');
}
/* Clicked/touched state */
#button_img:active {
background-image: url('button_on.png');
}
CSS will be much more performant and you will also be able to better separate concerns (display vs logic, etc).
JSBin: http://jsbin.com/beyin/1/
There is a way to get the vmouseup, vmousedown, vmousemove, vclick, etc. functionality of jQueryMobile without getting all the rest (and especially the side effects) of jquerymobile (i.e. enhancement, extra css, and the like)
Go to http://jquerymobile.com/download-builder/ (a tool for downloading a custom build of jquerymobile with only the components you need)
select ONLY "Virtual Mouse (vmouse) Bindings"
download it.
The download will contain only a single .js files (in both minimized and uncompressed version). No css.
Link this script in the head of your html after plain jquery, and use it like this:
<head>
<script src="http://code.jquery.com/ui/1.10.4/jquery-ui.min.js"></script>
<script src="whatever/path/jquery.mobile.custom.min.js"></script>
<script>
$(function(){ // or replace this with window.onload for that matter
// Your code here, e.g.
$("#button_img").on("vmousedown", function() {
/*whatever*/
});
// CAUTION: this won't work (see note below):
// $("#button_img").vmousedown(function(){/*whatever*/}); // WON'T WORK
});
</script>
</head>
NOTE: the methods .vmousedown(), .vmouseup(), etc. won't work. You have to bind the event listener with .on("vmousedown", ...).
Not sure why: I guess this is because the part of jquerymobile that creates shortcut methods with the same name as the events is in some other module. Maybe it is possible to figure out which module it is and include it in the download, but I think it would force you to include other undesired dependencies.
Use touchstart or touchend for touch devices.
Most times you want to catch touchstart as well as mousedown. You need to make sure though that the handler is only triggered once. The simplest way to do this is to catch them both and call e.preventDefault().
$("#button_img").on('touchstart mousedown', function(e) {
//your code...
e.preventDefault(); //prevents further events from being dispatched
}
Source: developer.mozilla.org:
If the browser fires both touch and mouse events because of a single user input, the browser must fire a touchstart before any mouse events. Consequently, if an application does not want mouse events fired on a specific touch target element, the element's touch event handlers should call preventDefault() and no additional mouse events will be dispatched.
I'm making an Javascript web app and I can't for the life of me get the touchstart event to fire. I get the touchmove and touchend events no problem. This is a problem because as I see it the best way to distinguish between a tap and a scrolling motion is to zero a counter on the touchstart event, update it at touchmove and then compare it at touchend. I'm doing this so I can do some action at the end of tap but not a scroll. For instance, it would be very confusing if a page opened for an item in a listed after you finished scrolling down that list, but it would be nice to be able to tap on an item to open its page.
This is what I have:
// FIXME: this doesn't seem to ever fire
el.addEventListener('touchstart', function(e) {
// make sure that at the start of every touch we're not considered to be moving
alert("Touch starting");
app.__touchMoving = 0;
}, false);
el.addEventListener('touchmove', function(e) {
app.__touchMoving++;
}, false);
el.addEventListener('touchend', function(e) {
alert("Touch ended. We moved beforehand this many times: " + app.__touchMoving);
// if we are moving
if (app.__touchMoving > 0) {
// stop, since we're dragging, not tapping
return false;
}
// else we're no longer moving, so it was a tap
}
I never see the touchstart alert. If I scroll the touchend will fire and app__touchMoving will have some sort of decent value. On a side note, I've noticed that sometimes the touchend will seem to fire multiple times.
Am I missing something basic here? Plenty of people say that this should work just fine on Android (and iPhone) yet the first listener never seems to fire.
Update: I should mention that I've been testing on a Samsung Galaxy S running Android 2.1.
I don't know if u can use it: iScroll