Smoothly movement - javascript

I want to make movement while button is clicked : left.
This is for mobile movement...
The problem its its move, but only once. I need to spam clicking button...
Code:
In create :
this.buttonleft.inputEnabled = true;
this.buttonleft.events.onInputDown.add(this.clickMoveLeft, this);
this.buttonleft.mouseDownCallback = false;
this.buttonleft.alpha = false; // Making no visable
Under everything - separate function :
clickMoveLeft: function()
{
if(!this.clickMoveLeft.mouseDownCallback)
{
this.player.body.velocity.x = -160;
this.buttonleft.mouseDownCallback = true;
}
else if (!this.clickMoveLeft.mouseUpCallback)
{
this.player.body.velocity.x = 0;
this.buttonleft.mouseDownCallback = false;
}

I don't know the phaser framework but, knowing how js events works and after a quick search in the docs I'm pretty sure that the .mouseDownCallback callback is fired just once when you click the mouse and isn't continuos.
So you can use the mousedown event to call a function that keep moving what you want to move and the mouseup to stop it.

Related

Have one button with two different behaviors for click and mouse down

I wish to have the same button behave different for left click and left mouse down.
On click it should add 15 to the current number, on mouse down it adds 1 for as long as the mouse is down
var value = 0;
document.getElementById("Addbtn").addEventListener("mousedown", mouseDown);
document.getElementById("Addbtn").addEventListener("click", mouseClick);
function mouseDown() {
this.value++;
document.getElementById("demo").innerHTML = this.value.tosSring();
}
function mouseClick() {
this.value += 15;
document.getElementById("demo").innerHTML = this.value.tosSring();
}
The problem both events gets fired and I wish to distinguish them so when mouse is hold down click won't fire and vise versa.
Is there a way to achieve this?
Cheers
As I said in the comment, since click and mousedown are related and there is no way to disconnect them from each other, the solution can come with a bit of a trick, adding a timeout to determine if it was a "long hold" of the mouse down.
Added a little bonus to disable the click if mouse down has been triggered, you can remove it if not needed.
Also notice, its on a 1 second waiting (1000 ms), change it according to how much you can wait before saying its a mousedown event. 1 second seems long to a user sometime ( about 500 ms is a sweet spot for me)
var value = 0;
var mouseHoldTimeout;
var mouseDownDone = false;
document.getElementById("Addbtn").addEventListener("mousedown", mouseDown);
document.getElementById("Addbtn").addEventListener("click", mouseClick);
function mouseDown() {
mouseHoldTimeout = setTimeout(() => {
value++;
mouseDownDone = true;
document.getElementById("demo").innerHTML = value.toString();
}, 1000);
}
function mouseClick() {
if (mouseHoldTimeout) {
clearTimeout(mouseHoldTimeout);
mouseHoldTimeout = null;
}
if (mouseDownDone) {
mouseDownDone = false;
return;
}
value += 15;
document.getElementById("demo").innerHTML = value.toString();
}
mousedown event will trigger when you click either the left or right or even the middle.It does not matter which one do you click it runs the function. In contrast click event will trigger when you click the left.So it seems when you click the left you trigger mousedown(for left) and click event.
As the document provides the click event triggers after mousedown and mouseup.
js mouse basics

Disable text selection on right click

I'm writing a desktop app using nwjs, and I want to use the right mouse button for some UI functions. This is working pretty ok right now; I am able to disable the context menu when the right click was for a UI function.
However, I am having an awful time figuring out how to not only stop right click events from opening a context menu, but also to stop them from selecting the text under the cursor.
Here is an example of what is happening (that I do not want to happen) - I am left-click dragging a handle to resize a UI view, and then while the left mouse is held down I am right clicking to cancel the resize. When the right click ends over any text, the text is selected. (Normally, a context menu would also appear.)
When handling the right mouse down event and context menu event, I am calling event.preventDefault() and returning false.
What the actual event handler code looks like (appearing in the same order as the events are spawned and handled)...
this.windowMouseDownListener = event => {
if(this.draggingResize &&
event.button === 2 && !event.ctrlKey
){
for(let view of this.area.views){
view.size = view.sizeBeforeDrag;
}
this.area.updateElementSizes();
this.draggingResize = false;
this.recentDraggingResize = true;
event.preventDefault();
event.stopPropagation();
return false;
}
};
this.windowContextMenuListener = event => {
if(this.recentDraggingResize){
event.preventDefault();
return false;
}
};
this.windowMouseUpListener = event => {
this.sizeBeforeDrag = this.size;
if(this.size <= 0.0001){
this.area.removeView(this);
}
if(this.draggingResize || this.recentDraggingResize){
this.recentDraggingResize = false;
this.draggingResize = false;
event.preventDefault();
event.stopPropagation();
return false;
}
};
How can I fix this behavior?

A Double Click event also triggers Click event in EaselJS

Adding Event Listener
function Solitaire() {
this.table.addEventListener("click", this.handleClick.bind(this));
this.table.addEventListener("dblclick", this.handleDoubleClick.bind(this));
}
Handling Event
Solitaire.prototype.handleDoubleClick = function(event) {
console.log("DoubleClick");
};
Solitaire.prototype.handleClick = function(event) {
console.log("Click");
};
Expected output (in console) on a double click event
DoubleClick
But the output I get in console:
Click
Click
DoubleClick
I don't know about easeljs, but I can tell you about how it is done in jQuery, where you need to "hack" it to make it actually work.
var DELAY = 500;
$('#my_element').on('click', function(e){
++clicks; // Count the clicks
if(clicks === 1){
// One click has been made
var myTimerToDetectDoubleClick = setTimeout(function(){
console.log('This was a single click');
doStuffForSingleClick();
clicks = 0;
}, DELAY);
} // End of if
else{
// Someone is clicking pretty damn fast, they probably mean double click :p
clearTimeout(myTimerToDetectDoubleClick);
doStuffForDoubleClick();
clicks = 0;
}
}).on('dblclick', function(evt){
evt.preventDefault(); // cancel system's default double click
});
The basic essence will remain the same for event handling for easeljs. You can imitate this behaviour accordingly there.

Define moving direction javascript (Android device)

I am writing PhoneGap application, and use swipe and scroll on one view. For scroll I use native scroll (I have tried to use iScroll, but there are many inputs in my view, so the better solution that I found it is a native scroll). For defining direction of moving I am gathering first 10 touchmove events in array and check clientX and clienY values and than define average value. And all should be good, but in Android touchmove event does not work is scroll view without preventDefault(). So, according this issue, I use preventDefault() for first ten touchmove events and than depending on direction continue use preventDefault() and make swipe, or don't use preventDefault() and make scroll. But when I make scroll nothing happens(. There is an example:
var list = document.querySelector('ul');
var arr = [];
var ev = document.createEvent('UIEvent');
var evEnd = document.createEvent('UIEvent');
var evCancel = document.createEvent('UIEvent');
var flag = false;
ev.initUIEvent("touchstart", true, true);
evEnd.initUIEvent("touchend", true, true);
evCancel.initUIEvent("touchcancel", true, true);
list.addEventListener('touchstart', startMove, false)
list.addEventListener('touchend', endMove, false)
function startMove(e){
list.addEventListener('touchmove', move, false)
}
function move(e){
if(flag){
return;
}
e.preventDefault();
arr.push(e);
if(arr.length>10){
flag = true;
list.dispatchEvent(evEnd);
list.dispatchEvent(evCancel);
list.dispatchEvent(ev);
return;
}
}
function endMove(e){
list.removeEventListener('touchmove', move, false)
list.removeEventListener('touchend', endMove, false)
}
http://jsfiddle.net/tnqHQ/17/

how to add dbclick() on right click in jquery

Hi I want to have a dblclick() on the right click as the google maps have to zoom in and zoom out. Is there any way to do that. I have written the dblclick but now its working with only left click. Any pointers on how to do this. Here is my code
$("div#demo1").dblclick(function(e) {
//alert(e.getElementById());
if( (!$.browser.msie && e.button == 0) || ($.browser.msie && e.button == 1) ) {
alert("Left Mouse Button was clicked on demo1 div!");
$("div.window").animate({
'height':'+=20', 'width':'+=20'
},0,function(){
jsPlumb.repaintEverything();
jsPlumb.repaintEverything();
});
// Left mouse button was clicked (all browsers)
}
else if( (!$.browser.msie && e.button == 2) || ($.browser.msie && e.button == 3) ) {
alert("right click double");
}
});
There is another way you could detect a double right-click that does not involve fiddling with timers or keeping track of click counts manually. Using the .detail property of the event object in a mouseup or mousedown event. .detail holds the click count which will tell you how many clicks have happened recently. If .detail === 2 it was a double-click.
// suppress the right-click menu
$('#target').on('contextmenu', function (evt) {
evt.preventDefault();
});
$('#target').mouseup(function (evt) {
if (evt.which === 3) { // right-click
/* if you wanted to be less strict about what
counts as a double click you could use
evt.originalEvent.detail > 1 instead */
if (evt.originalEvent.detail === 2) {
$(this).text('Double right-click');
} else if (evt.originalEvent.detail === 1) {
$(this).text('Single right-click');
}
}
});
You might notice that I am using evt.originalEvent.detail to access the property instead of just .detail. This is because jQuery provides it's own version of the event object which does not include .detail, but you can access the original event object that the browser returned via .originalEvent. If you were using pure JavaScript instead of jQuery you would just use evt.detail.
Here's a working example.
There is no real way to do it, you can emulate it by taking the default timer for double clicks which IIRC is 300ms:
function makeDoubleRightClickHandler( handler ) {
var timeout = 0, clicked = false;
return function(e) {
e.preventDefault();
if( clicked ) {
clearTimeout(timeout);
clicked = false;
return handler.apply( this, arguments );
}
else {
clicked = true;
timeout = setTimeout( function() {
clicked = false;
}, 300 );
}
};
}
$(document).contextmenu( makeDoubleRightClickHandler( function(e) {
console.log("double right click" );
}));
http://jsfiddle.net/5kvFG/2/
Because the right-click has meaning to the user agent that is outside the purview of javascript (the context menu), you're going to have to do some dancing around.
First, you should disable the context menu on the target element:
document.getElementById('demo1').oncontextmenu = function() {
return false;
};
Now, when we right click, there won't be the context menu messing up the second click.
Next, understand that "double-click right" does not, generally speaking, exist. Even though you can bind the dblclick event, that isn't a generic event. "Double-click" is, by definition, double-clicking with the left mouse button.
So, we'll have to use the mousedown event, check to see how many times the right has been clicked, and react after two. I created a small helper function that keeps track of the click count and resets the state after a short time-frame.
var RightClick = {
'sensitivity':350,
'count':0,
'timer':false,
'active':function () {
this.count++;
this.timer = setTimeout(
this.endCountdown.bind(this),
this.sensitivity
);
},
'endCountdown': function () {
this.count = 0;
this.timer = false;
}
};
$("div#demo1").mousedown(function(e) {
if(e.which == 3) {
RightClick.active();
if (RightClick.count == 2)
alert("right click double");
}
});
Try it here: http://jsfiddle.net/94L7z/
You can adjust the sensitivity rate, allowing for shorter or longer double-clicks, depending on your preference.
Documentation
element.onContextMenu on MDN - https://developer.mozilla.org/en-US/docs/DOM/window.oncontextmenu
element.onMouseDown on MDN - https://developer.mozilla.org/en-US/docs/DOM/element.onmousedown
window.setTimeout on MDN - https://developer.mozilla.org/en-US/docs/DOM/window.setTimeout
jQuery event.which - http://api.jquery.com/event.which/
"Javascript Madness: Mouse Events" on UnixPapa.com, an article showing some tests related to mouse events and the left/right buttons - http://unixpapa.com/js/mouse.html
The problem is the concept of double clicking is only relevant to the left mouse button as far as JS is concerned. So no matter how many time, and how fast you click the right mouse button, it just registers as a bunch of single clicks. So what to do?
Create a global variable to track click count
detect a single right-click, you already know how to do this it seems
set the global variable that the right-click was fired once
set a timeout, so if another right click doesn't come through in a
reasonable time to be considered a dblclick the global variable
resets to 0. I recommend 300 ms, it seems to be the most natural
each time a right-click registers check that variable, if it's more
than one, fire your double-right-click handler.
you may want to make that global variable an object so you can track which element
registered the right click and expire specific element right clicks
accordingly. This will allow you to ignore if they double click
while moving the mouse over various objects. I consider this
optional as the chain of events are unlikely for a user to follow,
but depending on your app may result in unexpected functionality.
It might be better to define a jQuery function with this (try it):
var precision = 400;
var lastClickTime = 0;
$(document).ready(function()
{
var div = $('#div');
$(div).bind("contextmenu", function(e)
{
return false;
});
$(div).mousedown(function(event)
{
if (event.which == 3)
{
var time = new Date().getTime();
if(time - lastClickTime <= precision)
{
// DOUBLE RIGHT CLICK
alert('double click');
}
lastClickTime = time;
}
});
});

Categories