I'm working on a html5 canvas game, but I don't know how to handle touch events. When a user touch the screen, and drag, then the browser will scroll the page. I would like to prevent it, and get the touch start, and touch end position. Is it possible?
Thanks in advance
You need to override the default touch behaviour to stop touchevents dragging the page. Clearly, you'll need to handle them again if your page becomes larger than the available area, but as you're making a game, going to assume you're doing 100%/100% layout.
function preventBehavior(e) {
e.preventDefault();
};
document.addEventListener("touchmove", preventBehavior, {passive: false});
Edit: here's the W3C recommendation talking about touch events, which might be handy for you.
Due to breaking changes made in recent versions of Chrome, the above answers are no longer correct. Attaching a touch event listener to the document or body elements will cause the event listener to be registered in "passive" mode, which causes calls to preventDefault to be ignored.
There are two solutions:
The preferred solution is to use the CSS style touch-action to specify that no scrolling should happen (e.g. with the value "none")
In cases where this is not appropriate (e.g. if the type of interaction should change dynamically in a way that cannot be determined before the gesture begins) then the event listener must be registered with the third parameter set to { passive: false } (you should perform browser detection to ensure that this style is supported first, though).
If you don't want to use jQuery mobile or any other library then you can try this.
var startX, startY, endX, endY;
document.addEventListener("touchstart", function(e){
startX = e.touches[0].pageX;
startY = e.touches[0].pageY;
e.preventDefault();//Stops the default behavior
}, false);
document.addEventListener("touchend", function(e){
endX = e.touches[0].pageX;
endY = e.touches[0].pageY;
e.preventDefault();//Stops the default behavior
}, false);
canvas.addEventListener('touchstart', function(e)
{
alert(e.changedTouches[0].pageX + " " + e.changedTouches[0].pageY);
}
canvas.addEventListener('touchend', function(e)
{
alert(e.changedTouches[0].pageX + " " + e.changedTouches[0].pageY);
}
Here's a good article about touching and gesturing on mobile phones:
http://www.sitepen.com/blog/2008/07/10/touching-and-gesturing-on-the-iphone/
Following solution preventing scroll when dragging AND at the same time usual scroll is working (when not dragging)
var scrollable = true;
var listener = function(e) {
if (! scrollable) {
e.preventDefault();
}
}
document.addEventListener('touchmove', listener, { passive:false });
onDragstartHandler() {
scrollable = false;
}
onDragendHandler(} {
scrollable = true;
}
Don't forget to bind onDragstartHandler and onDragendHandler to related elements
Related
Working on a website that is also viewable on mobile and need to bind an action on both touchstart and mousedown.
Looks like this
$("#roll").bind("mousedown touchstart", function(event){
someAction();
It works fine on Iphone, but on Android it responds twice.
event.stopPropagation();
event.preventDefault();
Adding this code fixed it for Android Chrome, but NOT for Android default browser. Any other tricks that can fix the problem for all android?
element.on('touchstart mousedown', function(e) {
e.preventDefault();
someAction();
});
preventDefault cancels the event, as per specs
You get touchstart, but once you cancel it you no longer get mousedown. Contrary to what the accepted answer says, you don't need to call stopPropagation unless it's something you need. The event will propagate normally even when cancelled. The browser will ignore it, but your hooks will still work.
Mozilla agrees with me on this one:
calling preventDefault() on a touchstart or the first touchmove event of a series prevents the corresponding mouse events from firing
EDIT: I just read the question again and you say that you already did this and it didn't fix the Android default browser. Not sure how the accepted answer helped, as it does the same thing basically, just in a more complicated way and with an event propagation bug (touchstart doesn't propagate, but click does)
I have been using this function:
//touch click helper
(function ($) {
$.fn.tclick = function (onclick) {
this.bind("touchstart", function (e) {
onclick.call(this, e);
e.stopPropagation();
e.preventDefault();
});
this.bind("click", function (e) {
onclick.call(this, e); //substitute mousedown event for exact same result as touchstart
});
return this;
};
})(jQuery);
UPDATE: Modified answer to support mouse and touch events together.
taking gregers comment on win8 and chrome/firefox into account, skyisred's comment doesn't look that dumb after all (:P # all the haters)
though I would rather go with a blacklist than with a whitelist which he suggested, only excluding Android from touch-binds:
var ua = navigator.userAgent.toLowerCase(),
isAndroid = ua.indexOf("android") != -1,
supportsPointer = !!window.navigator.msPointerEnabled,
ev_pointer = function(e) { ... }, // function to handle IE10's pointer events
ev_touch = function(e) { ... }, // function to handle touch events
ev_mouse = function(e) { ... }; // function to handle mouse events
if (supportsPointer) { // IE10 / Pointer Events
// reset binds
$("yourSelectorHere").on('MSPointerDown MSPointerMove MSPointerUp', ev_pointer);
} else {
$("yourSelectorHere").on('touchstart touchmove touchend', ev_touch); // touch events
if(!isAndroid) {
// in androids native browser mouse events are sometimes triggered directly w/o a preceding touchevent (most likely a bug)
// bug confirmed in android 4.0.3 and 4.1.2
$("yourSelectorHere").on('mousedown mousemove mouseup mouseleave', ev_mouse); // mouse events
}
}
BTW: I found that mouse-events are NOT always triggered (if stopPropagation and preventDefault were used), specifically I only noticed an extra mousemove directly before a touchend event... really weird bug but the above code fixed it for me across all (tested OSX, Win, iOS 5+6, Android 2+4 each with native browser, Chrome, Firefox, IE, Safari and Opera, if available) platforms.
Wow, so many answers in this and the related question, but non of them worked for me (Chrome, mobil responsive, mousedown + touchstart). But this:
(e) => {
if(typeof(window.ontouchstart) != 'undefined' && e.type == 'mousedown') return;
// do anything...
}
Fixed using this code
var mobile = /Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent);
var start = mobile ? "touchstart" : "mousedown";
$("#roll").bind(start, function(event){
This is a very old question but I came across the same problem and found another solution that does not stopPropagation(), preventDefault() or sniff the type of device. I work on this solution with the assumption that the device supports both touch and mouse inputs.
Explanation: When a touch is initiated, the order of events is 1) touchstart 2) touchmove 3) touchend 4) mousemove 5) mousedown 6) mouseup 7) click. Based on this, we will mark a touch interaction from touchstart (first in chain) until click (last in chain). If a mousedown is registered outside of this touch interaction, it is safe to be picked up.
Below is the logic in Dart, should be very replicable in js.
var touchStarted = false;
document.onMouseDown.listen((evt) {
if (!touchStarted) processInput(evt);
});
document.onClick.listen((evt) {
touchStarted = false;
});
document.onTouchStart.listen((evt) {
touchStarted = true;
processInput(evt);
});
As you can see my listeners are placed on document. It is thus crucial that I do not stopPropagation() or preventDefault() these events so they can bubble up to other elements. This solution helped me single out one interaction to act on and hope it helps you too!
I recommend you try jquery-fast-click. I tried the other approach on this question and others. Each fixed one issue, and introduced another. fast-click worked the first time on Android, ios, desktop, and desktop touch browsers (groan).
Write this code and add j query punch touch js.it will work simulate mouse events with touch events
function touchHandler(event)
{
var touches = event.changedTouches,
first = touches[0],
type = "";
switch(event.type)
{
case "touchstart": type = "mousedown"; break;
case "touchmove": type="mousemove"; break;
case "touchend": type="mouseup"; break;
default: return;
}
var simulatedEvent = document.createEvent("MouseEvent");
simulatedEvent.initMouseEvent(type, true, true, window, 1,
first.screenX, first.screenY,
first.clientX, first.clientY, false,
false, false, false, 0/*left*/, null);
first.target.dispatchEvent(simulatedEvent);
event.preventDefault();
}
function init()
{
document.addEventListener("touchstart", touchHandler, true);
document.addEventListener("touchmove", touchHandler, true);
document.addEventListener("touchend", touchHandler, true);
document.addEventListener("touchcancel", touchHandler, true);
}
This native solution worked best for me:
Add a touchstart event to the document settings a global touch = true.
In the mousedown/touchstart handler, prevent all mousedown events when a touch screen is detected: if (touch && e.type === 'mousedown') return;
I think the best way is :
var hasTouchStartEvent = 'ontouchstart' in document.createElement( 'div' );
document.addEventListener( hasTouchStartEvent ? 'touchstart' : 'mousedown', function( e ) {
console.log( e.touches ? 'TouchEvent' : 'MouseEvent' );
}, false );
I am developing an HTML5 Canvas project and while adding multitouch support for mobile devices, I seem to have run into an issue on Mobile Safari in iOS 7.1.
The main way that users interact with my app is by clicking and dragging. On the desktop, I add the appropriate mouse event listeners to my canvas...
c.addEventListener('mousedown', mouseDown, false);
c.addEventListener('mousemove', mouseMoved, false);
c.addEventListener('mouseup', mouseUp, false);
... have these event handlers calculate mouse position and call out to a more generic function that just accepts the X and Y position of the event...
function mouseDown(evt)
{
var pos = getMousePos(evt);
inputDown(pos);
}
function mouseUp(evt)
{
var pos = getMousePos(evt);
inputUp(pos);
}
function mouseMoved(evt)
{
var pos = getMousePos(evt);
inputMoved(pos);
}
function getMousePos(evt)
{
var rect = c.getBoundingClientRect();
return { 'x': evt.clientX - rect.left, 'y': evt.clientY - rect.top }
}
... and everything works great. I designed this level of abstraction to allow for easy expansion to other input methods. So now I attempt to use the Touch API to expand this. First I add my handlers to the canvas right next to the mouse handlers...
c.addEventListener("touchstart", touchDown, false);
c.addEventListener("touchmove", touchMoved, false);
c.addEventListener("touchend", touchUp, false);
c.addEventListener("touchcancel", touchUp, false);
... then add my thin event handlers to abstract away the touch events ...
function touchDown(evt)
{
evt.preventDefault();
// Ignore touches after the first.
if (activeTouch != null)
return;
if (evt.changedTouches.length > 0)
{
activeTouch = evt.changedTouches[0].identifier;
var pos = getTouchPos(evt);
inputDown(pos);
}
}
function touchUp(evt)
{
var pos = getTouchPos(evt);
activeTouch = null;
inputUp(pos);
}
function touchMoved(evt)
{
var pos = getTouchPos(evt);
inputMoved(pos);
}
function getTouchPos(evt)
{
var canX = 0;
var canY = 0;
for( var i = 0; i < evt.touches.length; i++ )
{
if (evt.touches[i].identifier == activeTouch)
{
canX = evt.touches[i].pageX - c.offsetLeft;
canY = evt.touches[i].pageY - c.offsetTop;
break;
}
}
return { 'x': canX, 'y': canY }
}
... and this is where I run into trouble! You can see things get a little hairy but inefficiencies aside, I think I am using everything correctly. The problem is that getTouchPos(evt) seems unable to get the correct X, Y position of a touch on touchstart. On my first touch, I get a position of 0,0. If I drag my finger, the touchmove fires multiple times and the X,Y coordinates reported seem fine. If I lift my finger, touchend fires and I also get a correct location. However, if I touch again, touchstart fires and rather than where I am touching, I get the X,Y coordinates of where my last touch ended!
I've gone in with a debugger and sure enough, the stale/uninitialized values are right there in the Touch objects I get in the event data. Am I doing anything obviously wrong? I don't understand why I seem to be getting bad coordinates from touchstart events. What can I do to work around this issue? Is there another source I can use to get the correct position? A subtle tweak to event order?
Here's a link to an online demo of the full code if you'd like to run some in-browser debug.
And thanks in advance for any help.
I'm not sure if it's obvious, but it was a fun issue to debug. So basically, the confusion comes down to this guy:
function mouseMoved(evt) {
var pos = getMousePos(evt);
inputMoved(pos);
}
For your mouse events, everything works great, because you're bound to mousemove.
c.addEventListener('mousemove', mouseMoved, false);
Which calls
function mouseMoved(evt) {
var pos = getMousePos(evt);
inputMoved(pos);
}
So, as you move your mouse around, your posX/posY values are updated continuously. (Hopefully you see the issue now :)
For TouchEvents, when a user touches (but does not move), you only trigger touchstart and touchend. It isn't until a user drags, that touchmove gets called, which in turn calls the function touchMoved (that calls inputMoved - which updates your posX/posY values).
The easiest way to address this issue on your page is just to call inputMoved in both touchstart and touchmove so your MassHaver instance has the latest state.
I wonder if its possible to prevent double-tap-to-zoom and double-tap-to-center on a specific HTML element in Safari iOS (iPad 1) ?
Because my small HTML5 game forces users to make fast clicks (or taps), which are interpreted as double clicks, and when it happens - the page changes zoom and centers itself.
Detecting double clicks (like in this answer - Safari iPad : prevent zoom on double-tap) smells bad..
Wrong answer #1:
<meta name="viewport" content="width=device-width, minimum-scale=1.0, maximum-scale=1.0, user-scalable=no"> - does not suit my purposes, because it will block any zoom.
Wrong answer #2: maybe would .preventDefault() on click event alone be enough for that ? - Does not have any effect.
There's no other way than catching the events you want to prevent, and call preventDefault() on them, as you had already more or less figured out.
Indeed, some particular CSS properties / values may change the global site behavior (fixed width or fixed, for example), but you're not safe from changes to the OS (see fixedhandling change in iOS5), nor do these changes necessarily prevent all behavior (pinch might be off, but not double-tapping).
So, the best way to disable default behavior only for double-tapping is to take advantage of the count of touches iOS provides: if we have only one contact, then we're tapping. Two, this means we're pinching.
The following setup code provides that functionality:
var elm = document.body; // or some selection of the element you want to disable
var catcher = function(evt) {
if (evt.touches.length < 2)
evt.preventDefault();
};
elm.addEventListener('touchstart', catcher, true);
Demo on jsFiddle.
Note: the third parameter (true) to addEventListener means that we want to capture events, that is catch them all, even for our descendant children.
I am preventing doubletaps like this:
var doubleTouchStartTimestamp = 0;
$(document).bind("touchstart", function (event) {
var now = +(new Date());
if (doubleTouchStartTimestamp + 500 > now) {
event.preventDefault();
}
doubleTouchStartTimestamp = now;
});
The elegance lies within the fact, that no timeouts are needed. I only update a timestamp. It only gets compared on the next touchstart. Works for me on iOS 6.
Doubletaps further down the dom are not affected.
The same works without jQuery, as well:
var doubleTouchStartTimestamp = 0;
document.addEventListener("touchstart", function (event) {
var now = +(new Date());
if (doubleTouchStartTimestamp + 500 > now) {
event.preventDefault();
}
doubleTouchStartTimestamp = now;
});
I wrote a jQuery plugin for the same purpose - selectively disabling double-tap zoom on given page elements (in my case, navigation buttons to flip pages) I want to respond to every tap (including double-tap) as a normal click event, with no iOS "touch magic", no matter how fast the user clicks it.
To use it, just run something like $('.prev,.next').nodoubletapzoom(); on the elements you care for. The principle it uses is to listen for consecutive touchstart events on a node within 500ms, and running event.preventDefault() on the second, unless other touches are active at the same time. As that preventDefault consumes both touches, we also synthesize the two "missed" click events for the node, so your intended touch action happens as many times as the user intended.
Apple has a lot of tips with specialized tags for webkit (Safari). View Official Docs
What iOS version/Safari browser are you using? That site most definitely does not let you double-tap. I found some CSS but haven't had time to try it as I'm about to step out:
body {
-webkit-text-size-adjust:none;
margin:0px;
}
div{
clear:both!important;
display:block!important;
width:100%!important;
float:none!important;
margin:0!important;
padding:0!important;
}
You will need to implement a double tap function and preventDefault on the second tap. Here is some tested code that uses global variables that should get you started:
<button id="test1">Double Tap Me!</button>
<div id="test2">EMPTY</div>
var elm1 = document.getElementById('test1');
var elm2 = document.getElementById('test2');
var timeout;
var lastTap = 0;
elm1.addEventListener('touchend', function(event) {
var currentTime = new Date().getTime();
var tapLength = currentTime - lastTap;
clearTimeout(timeout);
if (tapLength < 500 && tapLength > 0) {
elm2.innerHTML = 'Double Tap';
event.preventDefault();
} else {
elm2.innerHTML = 'Single Tap';
timeout = setTimeout(function() {
elm2.innerHTML = 'Single Tap (timeout)';
clearTimeout(timeout);
}, 500);
}
lastTap = currentTime;
});
And a fiddle: http://jsfiddle.net/brettwp/J4djY/
JQuery approach to disable Double Tap Zoom in MVC4
To Disable the double tap (double mouse down) functionality on iOS 1+ you need to catch the touchStart Event and create an override to prevent the zoom.
// Using Single script.js and JQuery.Mobile-1.2.0 UI each page in MVC gets assigned JQuery through delegates so you don't have to do a full refresh of the page allowing you to take advantage of the data-prefetch which loads the page in the DOM when the app loads for the first time
$(document).delegate("#CashRegister", "pageinit", function () {
// To Disable 'Pinch to Zoom' Note: don't implement gester event handlers if you want to
//keep pinch to zoom functionality NOTE: i use this as my pageinit is a delegate of a page
this.addEventListener("gesturestart", gestureStart, false);
this.addEventListener("gesturechange", gestureChange, false);
this.addEventListener("gestureend", gestureEnd, false);
//handle each event by disabling the defaults
function gestureStart(event) {
event.preventDefault();
}
function gestureChange(event) {
event.preventDefault();
}
function gestureEnd(event) {
event.preventDefault();
}
//Recreate Double Tap and preventDefault on it
$(this).bind('touchstart', function preventZoom(e) {
// recreate the double tab functionality
var t2 = e.timeStamp
, t1 = $(this).data('lastTouch') || t2
, dt = t2 - t1
, fingers = e.originalEvent.touches.length;
$(this).data('lastTouch', t2);
if (!dt || dt > 500 || fingers > 1) return; // not double-tap
e.preventDefault(); // double tap - prevent the zoom
// also synthesize click events we just swallowed up
$(this).trigger('click').trigger('click');
});
Actually, .preventDefault() definitely does work... using jQuery:
var InputHandler = {
startEventType : isTouch ? "touchstart" : "mousedown"
}
$(selector).bind(InputHandler.startEventType, function(evnt) {
evnt.preventDefault();
});
Your problem with trying to prevent on .click() is that the browser isn't throwing a "click" element. Safari only fires a click to help simulate a click... But when there's a double tab, Safair doesn't through a "click" element. Your event handler for .click() doesn't ever fire, and therefore the .preventDefault() doesn't fire either.
Anyone have any idea how to detect a mouseup event on a scrollbar? It works in FF, but not in Chrome or IE9.
I set up a quick demo: http://jsfiddle.net/2EE3P/
The overall idea is that I want to detect a scrollEnd event. There is obviously no such thing so I was going with a combination of mouseUp and timers, but mouseUp isn't firing in most browsers! The div contains a grid of items so when the user stops scrolling I want to adjust the scroll position to the nearest point that makes sense, e.g. the edge of the nearest cell. I don't, however, want to automatically adjust the position if they're in the middle of scrolling.
I'll also happily accept any answer that gives me the equivalent of scrollEnd
found a solution that works without timers but only if you are scrolling the complete window.
switch(event.type){
case 'mousedown':
_btnDown = true;
//THIS IS ONLY CAUSE MOUSEUP ON SCROLLBAR IS BUGGY
$(document).bind('mousemove',function(event){
if(event.pageX < ($(window).width() - 30)){
//mouse is off scrollbar
$(this).unbind(event);
$(this).trigger('mouseup');
}
});
break:
case 'mouseup':
//do whatever
_btnDown = false;
break;
}
pretty dirty .. but works.
Using jquery there is a .scroll event you can use. Maybe use a global variable to keep track of when .scrollTop() (it returns the number of pixels there are above the screen) has stopped changing? Still creates a race condition, but it should work.
Answering my own question so I can close it -- there is no good solution to this, so timers it is...
I was handling the same problem. For me IE9 don't emit mouseup event for scrollbars. So, I checked and on IE9 when you "mouseup" it emits a mousemove event. So what I did was monitor scrolling, and monitor mousemove. When user is scrolling, and a mousemove event happens, then I understand it as a mouseup event. Only do this check for IE9, cheching the proto property availability. The code will also run for Opera, but Opera has the mouseup and then no problem for me when both events happens. Here is the code, I write AngularJS + ZEPTO code, so get the idea and write your own code, don't expect to copy&paste this code directly:
// Global for scrolling timeout
var q;
// Action to do when stop scrolling
var updatePosition = function() {
// Put the code for stop scrolling action here
}
$(document).on('mousemove', function(e) {
console.log('MOUSE MOVE ' + e.pageX + ',' + e.pageY);
if(!('__proto__' in {})) {
// for IE only, because it dont have mouseup
if($scope.scrolling && $scope.mouse_down) {
console.log('FAKE MOUSE UP FOR IE');
// Only simulate the mouseup if mouse is down and scrolling
$scope.scrolling = false;
$scope.mouse_down = false;
// Update Position is the action i do when mouseup, stop scrolling
updatePostition();
}
}
});
$(window).on('scroll', function(){
console.log('SCROLLING');
// Set the scrolling flag to true
if(!$scope.scrolling) {
$scope.scrolling = true;
}
// Stop if for some reason you disabled the scrolling monitor
if(!$scope.monitor_scrolling) return;
// Monitor scroll with a timeout
// Update Position is the action i do when stop scrolling
var speed = 200;
$timeout.cancel(q);
q = $timeout(updatePostition, speed);
});
$(window).on('mousedown', function() {
console.log('MOUSE DOWN');
// Stop monitor scrolling
$scope.monitor_scroll = false;
// Set that user is mouse down
$scope.mouse_down = true;
});
$(window).on('mouseup', function() {
console.log('MOUSE UP');
// Enable scrolling monitor
$scope.monitor_scroll = true;
// Change mouse state
$scope.mouse_down = false;
// Action when stop scrolling
updatePostition();
});
Was fighting with this problem. My system also runs for mobile and I have a large horizontal scrolling, that always when user stop scrolling, it need to find the actual item the used is viewing and centralize this item on screen (updatePosition). Hope this can help you. This is to support IE9+, FF, Chorme and Opera, I'm not worrying with old browsers.
Best Regards
Is very late but.... there are solution with any scroll in any part of your page.... I do it with the next code...
onScroll = function(){
$(window).unbind("mouseup").one('mouseup',function(e) {
alert("scroll up")
});
};
$(window).bind("scroll", onScroll);
body{
height:5000px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
I'm using the YUI slider that operates with mouse move events. I want to make it respond to touchmove events (iPhone and Android). How can I produce a mouse move event when a touchmove event occurs? I'm hoping that just by adding some script at the top that touchmove events will get mapped to the mouse move events and I won't have to change anything with the slider.
I am sure this is what you want:
function touchHandler(event)
{
var touches = event.changedTouches,
first = touches[0],
type = "";
switch(event.type)
{
case "touchstart": type = "mousedown"; break;
case "touchmove": type = "mousemove"; break;
case "touchend": type = "mouseup"; break;
default: return;
}
// initMouseEvent(type, canBubble, cancelable, view, clickCount,
// screenX, screenY, clientX, clientY, ctrlKey,
// altKey, shiftKey, metaKey, button, relatedTarget);
var simulatedEvent = document.createEvent("MouseEvent");
simulatedEvent.initMouseEvent(type, true, true, window, 1,
first.screenX, first.screenY,
first.clientX, first.clientY, false,
false, false, false, 0/*left*/, null);
first.target.dispatchEvent(simulatedEvent);
event.preventDefault();
}
function init()
{
document.addEventListener("touchstart", touchHandler, true);
document.addEventListener("touchmove", touchHandler, true);
document.addEventListener("touchend", touchHandler, true);
document.addEventListener("touchcancel", touchHandler, true);
}
I've captured the touch events and then manually fired my own mouse events to match. Although the code isn't particularly general purpose as is, it should be trivial to adapt to most existing drag and drop libraries, and probably most existing mouse event code. Hopefully this idea will come in handy to people developing web applications for the iPhone.
Update:
In posting this, I noticed that calling preventDefault on all touch events will prevent links from working properly. The main reason to call preventDefault at all is to stop the phone from scrolling, and you can do that by calling it only on the touchmove callback. The only downside to doing it this way is that the iPhone will sometimes display its hover popup over the drag origin. If I discover a way to prevent that, I'll update this post.
Second Update:
I've found the CSS property to turn off the callout: -webkit-touch-callout.
I finally found a way to get this working using Mickey's solution but instead of his init function. Use the init function here.
function init() {
document.getElementById('filter_div').addEventListener("touchstart", touchHandler, true);
document.getElementById('filter_div').addEventListener("touchmove", touchHandler, true);
document.getElementById('filter_div').addEventListener("touchend", touchHandler, true);
document.getElementById('filter_div').addEventListener("touchcancel", touchHandler, true);
}
If you see 'filter_div' is the chart area where we have the chart range filter and only in that area do we want to rewrite our touch controls!
Thank you Mickey. It was a great solution.
Along the lines of #Mickey Shine's answer, Touch Punch provides mapping of touch events to click events. It's built to put this support into jQuery UI, but the code is informative.
For future users, who comeback here the following code might be used :
var eventMap = {};
(function(){
var eventReplacement = {
"mousedown": ["touchstart mousedown", "mousedown"],
"mouseup": ["touchend mouseup", "mouseup"],
"click": ["touchstart click", "click"],
"mousemove": ["touchmove mousemove", "mousemove"]
};
for (i in eventReplacement) {
if (typeof window["on" + eventReplacement[i][0]] == "object") {
eventMap[i] = eventReplacement[i][0];
}
else {
eventMap[i] = eventReplacement[i][1];
};
};
})();
And then in the events use like following :
$(".yourDiv").on(eventMap.mouseup, function(event) {
//your code
}
For making #Mickey's code work on Edge and internet explorer, add the following lines in .css of the element where you want the simulation to happen:
.areaWhereSimulationHappens {
overflow: hidden;
touch-action: none;
-ms-touch-action: none;
}
These lines prevent the default touch for edge and IE. But if you add it to the wrong element, then it also disables scroll (which happens by default on edge and IE on touch devices).
I just discovered this code resolving, i'm stuck on this situation in which I would like to put touch events and mouse event:
https://codepen.io/benstl/details/LYQjKvN
I supposed I have to add in te html the touchevents in the line :
div class="cube" onmousedown="grabOn(true)" onmouseup="grabOff()">
and on the javascript on :
document.addEventListener('mouseup', grabOff);
document.addEventListener('mousemove', handleMouseMove);
But there's also the grab function to link to either.