I need to use touch events for touch screens, and mouseevents for regular Desktop for my website using Snap SVG.
I have mouse events like :
_Button.mousedown(function(){
// Do Stuff
});
How can I easily switch to touch events such as 'touchstart' when my user comes from a tablet ?
I don't want to duplicate code, and checks if its a touchscreen, like having 20* times this kind of code :
_Button.mousedown(function(){
// Do Stuff
});
if ( touchSreenFlag === true) {
_Button.mousedown(function(){
// Do Stuff
});
}
Thx
Here we go :
SVGTHING.mouseup(function(e){
if (e.type === 'touchend') {
// Stop propagation : on touch devices the first click will be used and not the second.
e.stopPropagation();
e.preventDefault();
}
do_stuff();
});
Related
I'm making a simple player motion in Javascript canvas. (Up down left right)
I created 4 buttons on screen for mobile players. I used the following code for the buttons as I wanted to move the player until the button is released.
upBtn.addEventListeter('mousedown',()=>{
let interval=setInterval(()=>{
player.y--;
}, 50);
upBtn.addEventListener('mouseup',()=>{
clearInterval(interval);
});
});
The above code works perfectly when the buttons are clicked in a computer. But in mobile it is not working.
I also tried to use touchdown and touchup but it didn't work.
What changes should I make in the code to make it work in mobile also?
Thanks in advance
You're looking for touchstart and touchend
function upFunc(event) {
//prevents some devices to emulate the click event
event.preventDefault();
let interval=setInterval(()=>{
player.y--;
}, 50);
upBtn.addEventListener('mouseup',downFunc);
upBtn.addEventListener('touchend',downFunc);
}
function downFunc(e) {
e.preventDefault();
clearInterval(interval);
}
upBtn.addEventListeter('mousedown', upFunc);
upBtn.addEventListeter('touchstart', upFunc);
Note that to support both mouse and touch in vanilla js you'll have to add both event listeners.
Also, some devices emulate the mouse events, so you can use preventDefault() to make sure your functions fires only once.
I had a similar issue and eventually solved it. I don't remember all the details of how I got to the end result but here is the code I eventually used to get it to work.
It is for controlling a camera robot. Pressing and holding the forward arrow makes the robot move forward while the button is held down and stops as soon as the button is released.
It works both on PC browser and on smartphone browsers. I've only tried it on a couple of browsers on Samsung though.
It uses the onmousup and onmousedown for the PC while for the smartphone it is a bit more complicated using the touch events.
Also important is the oncontextmenu="absorbEvent_()" which prevents the context menu from appearing when you hold down a button.
<button id="moveForward"
onmousedown="moveForward_onmousedown()"
onmouseup="anyMovementButton_onmouseup()"
onmouseout="anyMovementButton_onmouseout()"
ontouchstart="moveForward_onmousedown()"
ontouchend="anyMovementButton_onmouseup()"
ontouchmove="anyMovementButton_onmouseout()"
ontouchcancel="anyMovementButton_onmouseout()"
oncontextmenu="absorbEvent_()">
<svg width="34" height="34">
<polygon points="2,32 17,2 32,32" style="fill:lime;stroke:purple;stroke-width:3;fill-rule:evenodd;"></polygon>
</svg>
</button>
function moveLeft_onmousedown() {startMovement('left' ); }
function moveReverse_onmousedown() {startMovement('reverse'); }
function moveForward_onmousedown() {startMovement('forward'); }
function moveRight_onmousedown() {startMovement('right' ); }
function tiltUp_onmousedown() { singleMove('up' ); }
function tiltDown_onmousedown() { singleMove('down' ); }
function anyMovementButton_onmouseup() {stopMovement();}
function anyMovementButton_onmouseout() {stopMovement();}
// this function is for preventing context menu on mobile browser
function absorbEvent_(event)
{
var e = event || window.event;
e.preventDefault && e.preventDefault();
e.stopPropagation && e.stopPropagation();
e.cancelBubble = true;
e.returnValue = false;
return false;
}
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 noticed that these function doesn't work good in Firefox, but does in Chrome.
I use these function in a game in Js to shoot bullet (left mouse click) and to create a fireball all around the player with the right click that burns everyone in a small radius.
document.onclick = function(event) {
if(!player){ //to avoid onclick to be used before calling Player();
return;
}
if(player.canAttack && player.distance >= 80) { //not for sword attack
performAttack(player);
player.canAttack = false;
}
if(player.distance < 80)
performAttack(player);
//event.preventDefault();
}
document.oncontextmenu = function(event) {
//hide default behaviour of right click -> no context menu popup
event.preventDefault();
if(player.obtainedGadjet > 0) {
player.pressingMouseRight = true;
performSpecialAttack(player);
}
}
In the performAttack function I set player.isStopped = true, so my updatePlayer() doesn't change player.x and player.y while he's attacking. The same for the fireball attack. I want my player stays there.
It works in chrome, my player stops, attacks,and then can moves again, but in Firefox if I right click it somethimes acts instead as I have left clicked, so shoot the magic ball, and maybe then the fireball too. Furthermore, my player ignore isStopped = true, it seems like in Firefox oncontextmenu has "lower priority" than other events.
Any idea?
Thanks
Please note that a click event contains information about which button was pressed. You can try yourself with something like:
document.addEventListener('click', function(ev){
console.log(ev.button);
});
And, yes, click events are fired when you right-click, even if you're doing something on related contextmenu events.
So your code should look a bit more like
document.addEventListener('click', function(ev){
if (ev.button === 0) {
// Perform primary action
} else if (ev.button === 2) {
// Perform secondary action
}
});
document.addEventListener('contextmenu', function(ev){
ev.preventDefault();
});
Using the same click event is advisable as said by Ivan. You may also want to read this other discussion here on SO about best practices and why it's not always good to disable default right click behaviour (i.e.: it's not always guaranteed to work).
I am using PhoneGap and I need to catch a "keyboard is showing" event on android phones.
I've found some threads saying to use the "showkeyboard" event. (This one for example : Show hide keyboard is not working propery in android phonegap)
My question : Is this an android event usable with phonegap? Is this a simple phonegap event? Is this a browser event? Is this a classical javascript event?
I don't find any doc on this event, and I need it because it's also firing on orientation change...
EDIT: I've found this, saying it's from android but undocumented : https://issues.apache.org/jira/browse/CB-6154
These events are from Android but are not documented. I've encountered some trouble with this so I recommend not using them.
For information, in order to make my function work, I've done something like this (this is just the general idea):
this._keyboardTimer;
document.addEventListener('showkeyboard', function (e) {
clearTimeout(this._keyboardTimer); // keep only the last event
this._keyboardTimer = setTimeout(function(oldOrientation){
if (oldOrientation != getOrientation()) {
/* this is an orientation event */
} else {
/* keyboard is really opening */
}
}.bind(this, getOrientation()), 200);
}.bind(this), false);
function getOrientation() {
return ( (window.orientation == 90) || (window.orientation == -90) )
? 'landscape'
: 'portrait';
};
And I've done the same thing with the 'hidekeyboard' event. Hope this will help.
[EDIT] There's another problem (yirk!): keyboards may be slightly differents. If the keyboard changes for a smaller: the 'hidekeyboard' event is fired....
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>