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).
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;
}
In my game, when I hold down the left mouse and move it around, the game will become very slow. Although the right mouse button has the exact same function, doing the same with right click does not cause the game to slow down. Tested in Mozilla Firefox, IE 10, and Google Chrome, all with same results.
I'm not going to provide code right now because I don't see any way it could be related to the code, although I don't remember this happening before.
Here's the mousedown code showing I am using the same methods and left click makes the game run slow, right click does not.
function domousedown(e) {
if(e.which == 1) {
clearInterval(mousedownID);
rightmousedown(e);
mousedownID = setInterval(function() {
this.rightmousedown(e);
}, 500);
} else if(e.which == 3 || e.button == 2){
clearInterval(mousedownID);
rightmousedown(e);
mousedownID = setInterval(function() {
this.rightmousedown(e);
}, 500);
}
//return false;
e.preventDefault();
}
Does anyone know why this is happening? Any help is appreciated.
Thanks!
Edit: Found the issue, although I still don't understand why it's only on left click. Apparently with a lot of mousemove events then holding down left click and pressing other buttons, it causes the game to slow down. To prevent it I'll need to rewrite some mousedown methods.
I'm trying to disable the mouse right click option. So i used contextmenu bind function to prevent it. This works fine but when shift is pressed along with the mosue right click the contextmenu bind function is not triggering but it shows the contextmenu. Means am not getting the alert but it shows the menu.
Here is the code i tried.
$(document).ready(function(){
$(document).bind("contextmenu",function(e){
alert('Context Menu event has fired!');
return false;
});
});
In order to capture the shift button press and mouse right click am doing the below code but this doesn't help. May be i am doing something wrong.
$(document).ready(function(){
$(document).bind("contextmenu",function(e){
alert('Context Menu event has fired!');
return false;
});
var shift = false;
jQuery(document).on("keydown", function(event) {
//check for shift key is pressed
if (event.which === 16) {
shift = true;
}
});
jQuery(document).mousedown(function(e) {
// e.which === 3 is for mouse right click
if (e.which === 3 && shift === true) {
console.log("both action are triggered");
return false; // how to stop the contextmenu action here
}
});
});
I tried giving the e.preventDefault instead of return false. I think the context menu event itself is not triggering in firefox when shift is clicked.
How to disable the mouse right click in this situation for firefox? Any help or clue will be much helpful
JSFIDDLE
NOTE
This is not happening in chrome. This is happening in firefox only. Is this a bug?
It's not a bug, it's a feature!
http://www.whatwg.org/specs/web-apps/current-work/multipage/interactive-elements.html#context-menus
User agents may provide means for bypassing the context menu
processing model, ensuring that the user can always access the UA's
default context menus. For example, the user agent could handle
right-clicks that have the Shift key depressed in such a way that it
does not fire the contextmenu event and instead always shows the
default context menu.
You will not be able to do this in Firefox, by design. It's annoying, especially for complex web apps and games, but it's hard-coded into the browser and there's not way to disable it in javascript (that I know of).
Blame the standards, not Mozilla.
Javascript code to disable mouse right click
<script language="javascript">
document.onmousedown=disableRightclick;
status="Disabled";
function disableRightclick(event)
{
if(event.button==2)
{
alert(status);
return false;
}
}
</script>
On the HTML Body tag set the oncontextmenu property to false.
<body oncontextmenu="return false">
...
</body>
Disclaimer: The link provided is the blog which i have written. Hope
this solves the problem.
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>