I'd like to set up Hammer.js so that I can respond to horizontal pan events. My first attempt looks like this:
var mc = new Hammer(document.body);
mc.on("panleft panright", runBind(this, 'updatePosition'));
mc.on("panend", runBind(this, 'finalisePosition'));
This almost gets the behaviour that I'm looking for: if I pan left or right, the updatePosition function is called, and when I stop panning the finalisePosition function is called.
But these functions are also triggered if the gesture drifts left or right while scrolling vertically. For example, suppose I touch near the top of the screen then drag my finger down half the screen: that should register as a scroll event. Now suppose that I continue by dragging diagonally: downwards and to the left. In this scenario, I'd like to ignore the horizontal part of the gesture and treat the gesture as a vertical scroll event only, but Hammer.js is triggering the panright and panleft events as before.
My next attempt looks like this:
var mc = new Hammer(document.body, {
recognizers: [
[Hammer.Swipe],
[
Hammer.Pan,
{event: 'panvertical', direction: Hammer.DIRECTION_VERTICAL}
],
[
Hammer.Pan, // RecognizerClass
{direction: Hammer.DIRECTION_HORIZONTAL}, // options
['swipe'], // recognizeWith
['panvertical'] // requireFailure
],
]
});
mc.on("panleft panright", runBind(this, 'updatePosition'));
mc.on("panend", runBind(this, 'finalisePosition'));
This specifies that the horizontal pan events should only be triggered if the panvertical event has failed. Sure enough, this prevents the problem I described above. If I begin a vertical scrolling gesture then start to move horizontally, the panleft and panright events are not triggered. But this version has a more serious probelem: the default scroll behaviour doesn't happen! As a result it's impossible to scroll the app.
Can anyone suggest a better solution?
I'm using Hammer.js version 2.0.4.
I've had the same problem and
I've managed to make it work with this really ugly code
var first = false, lock = false;
var containerHandler = function(event) {
if(event.type == 'panend' || event.type == 'pancancel') {
// iOS bug fix
lock = false;
first = false;
} else if(event.type == 'swipe' && event.direction & Hammer.DIRECTION_VERTICAL) {
// iOS bug fix
lock = true;
first = true;
}
else if(event.type == 'panmove') {
// iOS bug fix ...
if(first === false && event.direction & Hammer.DIRECTION_VERTICAL) {
lock = true;
}
first = true;
if(lock === true)
return;
//your code etc...
};
var focusMC = new Hammer.Manager(mainContainer[0], {domEvents:true});
var pan = new Hammer.Pan({threshold: 5, direction:Hammer.DIRECTION_HORIZONTAL});
focusMC.add( pan );
focusMC.on('panstart panmove panend pancancel swipe', containerHandler);
small threshold is important..
As far as I remember this issue was only on iOS Safari, but on WP it worked correctly even without this code
Edit: Instead of the solution above, try forcing the touch-action property
to pan-y
I'm keeping both answers as they should all work
Hammer.js will automatically infer a touch-action property based on your recognizers. This might make the application more responsive, but it won't prevent vertical page scrolling just because a user is interacting with the element.
I had the same problem you were having, and found a dead simple solution that works pretty well for a workaround.
var isScrolling = false;
var galleryHammer = new Hammer(element, {
recognizers: [
[Hammer.Pan, { direction: Hammer.DIRECTION_HORIZONTAL }]
]
});
// Making the event listener passive means we don't get any delays between
// the user scrolling and the browser having checked if it should prevent
// that event
window.addEventListener('scroll', function() {
isScrolling = true;
}, { passive: true });
window.addEventListener('touchend', function() {
isScrolling = false;
});
galleryHammer.on('pan', function(event) {
if (isScrolling) {
return;
}
// Normal logic...
});
This worked for me (the code comes from a class, and this.hm is simply an Hammer instance):
this.hm.on('panleft', function(e){ // ...and same for panright
if(e.pointerType == 'touch' && (Math.abs(e.deltaY) > Math.abs(e.deltaX))){ return false; }
// do stuff
}
The extra pointerType check is there because I didn't have any issue on desktop computer (mouse events). So the whole is applied ony on touch devices/events.
Good day all.
I'm having some problems with hoverintent.js a jquery plugin that handle the mouseOver events in a different way than normal.
Due to some complications, I can't modifiy anything but the js of this plugin, but I need to make it compliant with touch events and not only with mouseOver and mouseLeave.
after some debugs, I have managed to recognize this part of the code to be the one to modify:
var handleHover = function(e) {
// next three lines copied from jQuery.hover, ignore children onMouseOver/onMouseOut
var p = (e.type == "mouseover" ? e.fromElement : e.toElement) || e.relatedTarget;
while ( p && p != this ) { try { p = p.parentNode; } catch(e) { p = this; } }
if ( p == this ) { return false; }
// copy objects to be passed into t (required for event object to be passed in IE)
var ev = jQuery.extend({},e);
var ob = this;
// cancel hoverIntent timer if it exists
if (ob.hoverIntent_t) { ob.hoverIntent_t = clearTimeout(ob.hoverIntent_t); }
// else e.type == "onmouseover"
if (e.type == "mouseover") {
// set "previous" X and Y position based on initial entry point
pX = ev.pageX; pY = ev.pageY;
// update "current" X and Y position based on mousemove
$(ob).bind("mousemove",track);
// start polling interval (self-calling timeout) to compare mouse coordinates over time
if (ob.hoverIntent_s != 1) { ob.hoverIntent_t = setTimeout( function(){compare(ev,ob);} , cfg.interval );}
// else e.type == "onmouseout"
} else {
// unbind expensive mousemove event
$(ob).unbind("mousemove",track);
// if hoverIntent state is true, then call the mouseOut function after the specified delay
if (ob.hoverIntent_s == 1) { ob.hoverIntent_t = setTimeout( function(){delay(ev,ob);} , cfg.timeout );}
}
}
};
// bind the function to the two event listeners
return this.mouseover(handleHover).mouseout(handleHover);
what I've done so far is to make the function working different with mobiles:
var handleHover = function(e) {
isMobile = /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent);
if(isMobile){
console.log("Ismobile");
}else{
... Same code as before here ...
}
// bind the function to the two event listeners
return this.mouseover(handleHover).mouseout(handleHover);
and now i'm struck. I would like it to "change" its behavior to handle the touch, and not the mouse over event, so on mobiles I will need to touch the element, instead to hovering on it. May someone give me an help? Am I on the right way? Is it the right way to think of it?
unluckily I have only the possibility to change this file and some few more.
Recently i bumped into several problems with changing hoverIntent.js, and ended up in writing my own plugin: hoverDelay.js (much simpler, and less code). see if you can use it, and modify it to your own needs (and maybe contribute the mobile code to it :-)
I have added an event listener in JS to listen for keyup/keydown events, I am attempting to move a sprite across the HTML canvas. I have that mostly working, but the page is being scrolled when the user presses the arrow keys.
I am returning false, and that does not seem to work. In addition, my understanding is that returning false in this manner would disable arrow button scrolling for the entire page. I would like to only disable this while the user is interacting with the canvas itself.
Here is my event listener:
addEventListener('keydown', function(e){
move = false;
x = false;
y = false;
var keycode;
if (window.event) keycode = window.event.keyCode;
else if (e) keycode = e.which;
switch(keycode){
case 37:
move = true;
x = 'negative';
break;
case 38:
move = true;
y = 'negative'
break;
case 39:
move = true;
x = 'positive'
break;
case 40:
move = true;
y = 'positive'
break;
}
if(move){
animation.move(x,y);
}
return false;
})
Edit:
The below answer has a good idea of how to make sure that the canvas is focused, but I am still puzzled why returning false in my EventListener function which returns false is not disabling scrolling.
As long as you are giving your canvas focus somehow (ie canvas.tabIndex = 1;) then you can just add e.preventDefault() right before your return false and it will work.
Example:
http://jsfiddle.net/faAkN/
I had a similar problem, and came up with a fix.
Here's what I came up with:
function $(){
return document.querySelector.apply(document,arguments);
}
var canvas = $('canvas'),
keysDown = []; // You can also define this as an object, {}
canvas.tabIndex = 0;
canvas.onclick = function(e){
document.body.scrollTop = canvas.offsetTop; // scrolls to canvas element
canvas.focus(); // re-focuses canvas in case the scroll unfocused it
}
canvas.onkeydown = canvas.onkeyup = function(e){
keysDown[e.keyCode] = e.type == 'keydown';
e.preventDefault();
return false;
}
function isDown(key){
return keysDown[key];
}
function resetMap(){
keysDown = [];
return false;
}
To check if a key is down, use isDown(keycode) either in an interval loop or in a keydown function.
For a regular key listener:
canvas.onkeydown = canvas.onkeyup = function(e){
// [...]
if(isDown(17) && isDown(32)){ // Ctrl + Space
alert('Ctrl and Space were pressed');
resetMap();
}
e.preventDefault();
return false;
}
For a rapid key listener similar to ActionScript 2.0's Key.isDown
function KeyLoop(){
if(isDown(17) && isDown(32)){ // Ctrl + Space
console.log('Lots of text');
resetMap();
}
setTimeout(keyLoop,1000/24); // # 24 fps
}
keyLoop();
I put a different action here for two reasons: 1) Mixing alert() with a repeating interval is never a good idea, and 2) to demonstrate the lack of delay, which is what makes this similar to the AS2 Key.isDown() function. To see the logged text, bring up firebug or a regular JavaScript console. In Chrome, that's CtrlShiftJ. In Firefox, CtrlShiftK.
This should fix your scrolling problem by focusing on the element when you click the canvas. An added benefit is that you can check for multiple keys at once since you're using keysDown[] as an abstraction from the original event, making an 8-directional game easy to make.
Have you tried something like this?
<script type="text/javascript">
canvas_active = false;
</script>
<canvas onfocus="javascript: canvas_active = true;" onblur="javascript: canvas_active = false;" />
Then in your current method check to see if the canvas_active is true and if so, return false, else return true. This would only work if the canvas is focused the whole time they are moving it, of course.
Is there a way to detect if a mouse button is currently down in JavaScript?
I know about the "mousedown" event, but that's not what I need. Some time AFTER the mouse button is pressed, I want to be able to detect if it is still pressed down.
Is this possible?
Regarding Pax' solution: it doesn't work if user clicks more than one button intentionally or accidentally. Don't ask me how I know :-(.
The correct code should be like that:
var mouseDown = 0;
document.body.onmousedown = function() {
++mouseDown;
}
document.body.onmouseup = function() {
--mouseDown;
}
With the test like this:
if(mouseDown){
// crikey! isn't she a beauty?
}
If you want to know what button is pressed, be prepared to make mouseDown an array of counters and count them separately for separate buttons:
// let's pretend that a mouse doesn't have more than 9 buttons
var mouseDown = [0, 0, 0, 0, 0, 0, 0, 0, 0],
mouseDownCount = 0;
document.body.onmousedown = function(evt) {
++mouseDown[evt.button];
++mouseDownCount;
}
document.body.onmouseup = function(evt) {
--mouseDown[evt.button];
--mouseDownCount;
}
Now you can check what buttons were pressed exactly:
if(mouseDownCount){
// alright, let's lift the little bugger up!
for(var i = 0; i < mouseDown.length; ++i){
if(mouseDown[i]){
// we found it right there!
}
}
}
Now be warned that the code above would work only for standard-compliant browsers that pass you a button number starting from 0 and up. IE uses a bit mask of currently pressed buttons:
0 for "nothing is pressed"
1 for left
2 for right
4 for middle
and any combination of above, e.g., 5 for left + middle
So adjust your code accordingly! I leave it as an exercise.
And remember: IE uses a global event object called … "event".
Incidentally IE has a feature useful in your case: when other browsers send "button" only for mouse button events (onclick, onmousedown, and onmouseup), IE sends it with onmousemove too. So you can start listening for onmousemove when you need to know the button state, and check for evt.button as soon as you got it — now you know what mouse buttons were pressed:
// for IE only!
document.body.onmousemove = function(){
if(event.button){
// aha! we caught a feisty little sheila!
}
};
Of course you get nothing if she plays dead and not moving.
Relevant links:
MouseEvent's button (DOM 2)
MSDN's button
Update #1: I don't know why I carried over the document.body-style of code. It will be better to attach event handlers directly to the document.
This is an old question, and the answers here seem to mostly advocate for using mousedown and mouseup to keep track of whether a button is pressed. But as others have pointed out, mouseup will only fire when performed within the browser, which can lead to losing track of the button state.
However, MouseEvent (now) indicates which buttons are currently pushed:
For all modern browsers (including Safari v11.1+ [v11.3+ on iOS]), use MouseEvent.buttons
For Safari < 11.1 (11.3 on iOS), use MouseEvent.which (buttons will be undefined for Safari) Note: which uses different numbers from buttons for Right and Middle clicks.
When registered on document, mousemove will fire immediately as soon as the cursor reenters the browser, so if the user releases outside then the state will be updated as soon as they mouse back inside.
A simple implementation might look like:
var primaryMouseButtonDown = false;
function setPrimaryButtonState(e) {
var flags = e.buttons !== undefined ? e.buttons : e.which;
primaryMouseButtonDown = (flags & 1) === 1;
}
document.addEventListener("mousedown", setPrimaryButtonState);
document.addEventListener("mousemove", setPrimaryButtonState);
document.addEventListener("mouseup", setPrimaryButtonState);
That code tracks the state of the primary mouse button (typically the left), ignoring the state of other mouse buttons.
If more complicated scenarios are required (different buttons/multiple buttons/control keys), check out the MouseEvent docs.
I think the best approach to this is to keep your own record of the mouse button state, as follows:
var mouseDown = 0;
document.body.onmousedown = function() {
mouseDown = 1;
}
document.body.onmouseup = function() {
mouseDown = 0;
}
and then, later in your code:
if (mouseDown == 1) {
// the mouse is down, do what you have to do.
}
the solution isn't good.
one could "mousedown" on the document, then "mouseup" outside the browser, and on this case the browser would still be thinking the mouse is down.
the only good solution is using IE.event object.
I know this is an old post, but I thought the tracking of mouse button using mouse up/down felt a bit clunky, so I found an alternative that may appeal to some.
<style>
div.myDiv:active {
cursor: default;
}
</style>
<script>
function handleMove( div ) {
var style = getComputedStyle( div );
if (style.getPropertyValue('cursor') == 'default')
{
// You're down and moving here!
}
}
</script>
<div class='myDiv' onmousemove='handleMove(this);'>Click and drag me!</div>
The :active selector handles the mouse click much better than mouse up/down, you just need a way of reading that state in the onmousemove event. For that I needed to cheat and relied on the fact that the default cursor is "auto" and I just change it to "default", which is what auto selects by default.
You can use anything in the object that is returned by getComputedStyle that you can use as a flag without upsetting the look of your page e.g. border-color.
I would have liked to set my own user defined style in the :active section, but I couldn't get that to work. It would be better if it's possible.
If you're working within a complex page with existing mouse event handlers, I'd recommend handling the event on capture (instead of bubble). To do this, just set the 3rd parameter of addEventListener to true.
Additionally, you may want to check for event.which to ensure you're handling actual user interaction and not mouse events, e.g. elem.dispatchEvent(new Event('mousedown')).
var isMouseDown = false;
document.addEventListener('mousedown', function(event) {
if ( event.which ) isMouseDown = true;
}, true);
document.addEventListener('mouseup', function(event) {
if ( event.which ) isMouseDown = false;
}, true);
Add the handler to document (or window) instead of document.body is important b/c it ensures that mouseup events outside of the window are still recorded.
The following snippet will attempt to execute the "doStuff" function 2 seconds after the mouseDown event occurs in document.body. If the user lifts up the button, the mouseUp event will occur and cancel the delayed execution.
I'd advise using some method for cross-browser event attachment - setting the mousedown and mouseup properties explicitly was done to simplify the example.
function doStuff() {
// does something when mouse is down in body for longer than 2 seconds
}
var mousedownTimeout;
document.body.onmousedown = function() {
mousedownTimeout = window.setTimeout(doStuff, 2000);
}
document.body.onmouseup = function() {
window.clearTimeout(mousedownTimeout);
}
In case someone else runs into this, you can use .matches with the :active selector:
function mouseDown() {
return document.body.matches(":active");
}
Using the MouseEvent api, to check the pressed button, if any:
// Mouse buttons
document.addEventListener('mousedown', e => console.log(e.buttons))
// Keyboard keys
document.addEventListener('keydown', e => console.log(e.key))
Return:
A number representing one or more buttons. For more than one button
pressed simultaneously, the values are combined (e.g., 3 is primary +
secondary).
0 : No button or un-initialized
1 : Primary button (usually the left button)
2 : Secondary button (usually the right button)
4 : Auxilary button (usually the mouse wheel button or middle button)
8 : 4th button (typically the "Browser Back" button)
16 : 5th button (typically the "Browser Forward" button)
You can combine #Pax and my answers to also get the duration that the mouse has been down for:
var mousedownTimeout,
mousedown = 0;
document.body.onmousedown = function() {
mousedown = 0;
window.clearInterval(mousedownTimeout);
mousedownTimeout = window.setInterval(function() { mousedown += 200 }, 200);
}
document.body.onmouseup = function() {
mousedown = 0;
window.clearInterval(mousedownTimeout);
}
Then later:
if (mousedown >= 2000) {
// do something if the mousebutton has been down for at least 2 seconds
}
You need to handle the MouseDown and MouseUp and set some flag or something to track it "later down the road"... :(
Short and sweet
I'm not sure why none of the previous answers worked for me, but I came up with this solution during a eureka moment. It not only works, but it is also most elegant:
Add to body tag:
onmouseup="down=0;" onmousedown="down=1;"
Then test and execute myfunction() if down equals 1:
onmousemove="if (down==1) myfunction();"
Using jQuery, the following solution handles even the "drag off the page then release case".
$(document).mousedown(function(e) {
mouseDown = true;
}).mouseup(function(e) {
mouseDown = false;
}).mouseleave(function(e) {
mouseDown = false;
});
I don't know how it handles multiple mouse buttons.
If there were a way to start the click outside the window, then bring the mouse into the window, then this would probably not work properly there either.
As said #Jack, when mouseup happens outside of browser window, we are not aware of it...
This code (almost) worked for me:
window.addEventListener('mouseup', mouseUpHandler, false);
window.addEventListener('mousedown', mouseDownHandler, false);
Unfortunately, I won't get the mouseup event in one of those cases:
user simultaneously presses a keyboard key and a mouse button, releases mouse button outside of browser window then releases key.
user presses two mouse buttons simultaneously, releases one mouse button then the other one, both outside of browser window.
var mousedown = 0;
$(function(){
document.onmousedown = function(e){
mousedown = mousedown | getWindowStyleButton(e);
e = e || window.event;
console.log("Button: " + e.button + " Which: " + e.which + " MouseDown: " + mousedown);
}
document.onmouseup = function(e){
mousedown = mousedown ^ getWindowStyleButton(e);
e = e || window.event;
console.log("Button: " + e.button + " Which: " + e.which + " MouseDown: " + mousedown);
}
document.oncontextmenu = function(e){
// to suppress oncontextmenu because it blocks
// a mouseup when two buttons are pressed and
// the right-mouse button is released before
// the other button.
return false;
}
});
function getWindowStyleButton(e){
var button = 0;
if (e) {
if (e.button === 0) button = 1;
else if (e.button === 1) button = 4;
else if (e.button === 2) button = 2;
}else if (window.event){
button = window.event.button;
}
return button;
}
this cross-browser version works fine for me.
Below jQuery example, when mouse is over $('.element'), color is changing depending on which mouse button is pressed.
var clicableArea = {
init: function () {
var self = this;
('.element').mouseover(function (e) {
self.handlemouseClick(e, $(this));
}).mousedown(function (e) {
self.handlemouseClick(e, $(this));
});
},
handlemouseClick: function (e, element) {
if (e.buttons === 1) {//left button
element.css('background', '#f00');
}
if (e.buttons === 2) { //right buttom
element.css('background', 'none');
}
}
};
$(document).ready(function () {
clicableArea.init();
});
Well, you can't check if it's down after the event, but you can check if it's Up... If it's up.. it means that no longer is down :P lol
So the user presses the button down (onMouseDown event) ... and after that, you check if is up (onMouseUp). While it's not up, you can do what you need.
I'm creating a scrolling effect using JQuery and I'm wondering if it's possible to distinguish between the user scrolling vs. programmatically scrolling.
I have something like this:
$('#element').on('scroll',function(e){
$('#element').stop(true); // stop previous scrolling animation
$('#element').animate({ // start new scrolling animation (maybe different speed, different direction, etc)
scrollTop:...
});
});
However, this event is triggered during every step of the animation. How can I tell if this event was triggered by the user or by the animation?
Use a variable to determine when you are scrolling programmatically
Example:
var programScrolling = false;
$('#element').on('scroll',function(e){
if (programScrolling) {
return;
}
$('#element').stop(true); // stop scrolling animation
programScrolling = true;
$('#element').animate({
scrollTop:...
});
programScrolling = false;
});
Not sure if that is exactly what you want, but the concept should work.
I would make functions for different kinds of scrollings to detect them and call a scroll handler for all of them, like so:
JS Fiddle
$(window).bind('mousewheel DOMMouseScroll', function(event){
var direction;
if (event.originalEvent.wheelDelta > 0 || event.originalEvent.detail < 0) {
direction = 'up';
}
else {
direction = 'down';
}
scrollHandler(direction, 'mouseWheel');
event.preventDefault();
});
var scrollHandler = function(direction, origin) {
var height = $(document).scrollTop();
var movement = (direction == 'up') ? -100 : 100;
console.log(origin);
$('body').stop(true);
$('body').animate({
scrollTop: height + movement
}, 250);
};
Then you can do different stuff according to the origin of the event!
You could also check if the user scrolls to the same direction that the screen is scrolling and do something different, or whatever you want with the info passed by the mousewheel event.
Original mousewheel event function copied from THIS answer
I would suggest possibly using the .originalEvent method. The downside is, this is very browser dependent. See here. Hopefully the following helps:
$('#element').scroll(function(e){
var humanScroll = e.originalEvent === undefined;
if(humanScroll) {
$(this).stop(true);
}
})