JavaScript: translate long tap events to right click events - javascript

How can one automatically translate long tap events to right click events? Since many touch devices like the iPad don't provide a way to do a right click on a website this would be very handy because a website's code doesn't need to be adjusted.
For example this code is designed for desktop browser having mouse support:
<html>
<head><title>Long tap to right click test</title></head>
<body>
<img src="dummy.png" oncontextmenu="alert('Hi!'); return false;" width="20" height="20" />
</body>
</html>
The goal is to translate a long tap event to the right click event without modifying the code. (Just loading some JavaScript, of course.)
If've seen that https://github.com/furf/jquery-ui-touch-punch/ does something similar for drag'n'drop support on jQuery widgets. However this plugin doesn't support the long tap.
Also http://code.google.com/p/jquery-ui-for-ipad-and-iphone/ does actually perform the desired translation but it brakes scrolling, thus making it useless for regular websites with the need of scroll support.
Any help is appreciated - thanks!

You can write simple plugin to handle this type of events. Lets call it longTap event. Example:
$.fn.longTap = function(options) {
options = $.extend({
delay: 1000,
onRelease: null
}, options);
var eventType = {
mousedown: 'ontouchstart' in window ? 'touchstart' : 'mousedown',
mouseup: 'ontouchend' in window ? 'touchend' : 'mouseup'
};
return this.each(function() {
$(this).on(eventType.mousedown + '.longtap', function() {
$(this).data('touchstart', +new Date);
})
.on(eventType.mouseup + '.longtap', function(e) {
var now = +new Date,
than = $(this).data('touchstart');
now - than >= options.delay && options.onRelease && options.onRelease.call(this, e);
});
});
};
Obviously you want to change mousedown and mouseup to touchstart and touchend in case of iPad.
Usage: http://jsfiddle.net/dfsq/RZgxT/1/

You can use a timeout for that:
var timeoutLongTouch;
var $mydiv = $j('#myDiv');
// Listen to mousedown event
$mydiv.on('mousedown.LongTouch', function () {
timeoutLongTouch = setTimeout(function () {
$mydiv.trigger('contextmenu');
}, 1000);
})
// Listen to mouseup event
.on('mouseup.LongTouch', function () {
// Prevent long touch
clearTimeout(timeoutLongTouch);
});

All solutions not work in desktop browsers.
You should also tune up 'click' handler behaviour, cause all 'longtap' events should also be followed by 'click' event.
In this case something code like this:
itemEl.click(function(event){
if ($(this).data('itemlongtouch')){
$(this).data('itemlongtouch', false);
}else{
//some work
}
});
itemEl.longTap(function(event){
$(this).data('itemlongtouch', true);
//some work
});

Related

Find if device is touch screen then apply touch event instead of click event

I am creating a phonegap application, but as I came to know that it takes 300MS to trigger click event instead of touchevent.
I don't want to apply both event. Is there any way to know if it's touch device without modernizer.
Here is jquery code for assumption
$('#id').on('click',funciton(e){
alert('id was clicked');
});
is there anyway to do it with pure JS/jQuery as phonegap application already takes more memory I want to use less library as I can.
I mean really you should Modernizr but...
var supportsTouch = 'ontouchstart' in window || navigator.msMaxTouchPoints;
var eventType = supportsTouch ? 'ontouchstart' : 'click';
Then declare your event listeners as such:
$('#id').on(eventType, function(e) {
alert('id was clicked');
});
This should eliminate the 300ms delay and trigger simulated clicks on desktop and touch devices :
$('#id').on('mousedown touchstart', function() {
$(this).one('mouseup touchend', function() {
alert('id was clicked');
});
});
If the item has a link in it (normally triggered by click), it would need some adaptation :
$('#id a').on('mousedown touchstart', function() {
var destination = this.attr('href');
$(this).one('mouseup touchend', function() {
if (destination) window.location = destination;
});
});
Edit - already having an accepted answer, this reply was more of an additional note. But nirmal was correct in the comments that touch devices emulating mouse events might lead to complications. The above code is therefore better suited to use with touch events only.
To be more complete with this answer, I'll post my approach for handling both touch and mouse events simultaneously. Either sequence will then trigger a custom event named page:tap. Listening for these simulated clicks can then be done as follows:
$(subject).on('page:tap', function() { ... });
Mouse and touch events are separated and any emulation triggering additional events is prevented by adding a class to body in between touchend and click, removing it again when the latter occurs.
var root = $('body'), subject = '#example_1, #example_2';
$(document).on('mousedown touchstart', subject, function(e) {
if (e.type == 'mousedown' && e.which != 1) return; // only respond to left clicks
var mean = $(e.currentTarget);
mean.one('mouseup touchend', function(e) {
if (e.type == 'touchend' && !root.hasClass('punch')) root.addClass('punch');
else if (root.hasClass('punch')) return;
mean.trigger('page:tap');
});
})
.on('click', subject, function() {
root.removeClass('punch');
return false;
});
One could also choose to add the class to the active element itself or html for example, that depends a bit on the setup as a whole.
Apply fastclick to your application. You'll find a .js file and a documentation over there. The shortest (jQuery) way of implementing that would be:
$(function() {
FastClick.attach(document.body);
});
If you don't use jQuery, you can choose the other way:
if ('addEventListener' in document) {
document.addEventListener('DOMContentLoaded', function() {
FastClick.attach(document.body);
}, false);
}
Let me know if you need further help!
This is the direct link to the fastclick.js file
You can try:
var clickEvent = ((document.ontouchstart!==null)?'click':'touchstart');
$("#mylink").on(clickEvent, myClickHandler);
for anyone coming here in 2021, use pointers events, and check pointerType to distinguish between mouse, touch, and pen.

How to add swipe feature to a image gallery?

I have an image gallery and I want to add swipe feature to it,next and prev big image. I don't want to use any pluggin. I have some code, I tried some but I was unable to make it work. Any advice is highly appreciated.
$(document).on("pagecreate","#pageone",function(){
$("img").on("swipeleft",function(){
console.log("Left");
});
$("img").on("swiperight",function(){
console.log("Right");
});
});
Jsfiddle
Thanks!
the swipeleft event listener is not available with only jQuery. You can use jQuery Mobile, or craft your own using the touchstart, touchmove, and touchend. Assuming you only want to execute something once, the following code should do:
var swiping = false;
$('#div').on('touchmove', function (event) {
swiping = true;
})
$('#div').on('touchstart', function (event) {
setTimeout(function() {
if ( swiping = true ) {
console.log('swiping');
}
}, 50)
})
The setTimeout likely isn't necessary since touchmove begins at the same time as touchstart - but I left it there in case any given browser performs differently.

How to detect the dragleave event in Firefox when dragging outside the window

Firefox doesn't properly trigger the dragleave event when dragging outside of the window:
https://bugzilla.mozilla.org/show_bug.cgi?id=665704
https://bugzilla.mozilla.org/show_bug.cgi?id=656164
I'm trying to develop a workaround for this (which I know is possible because Gmail is doing it), but the only thing I can come up with seems really hackish.
One way of knowing when dragging outside the window has occurred it to wait for the dragover event to stop firing (because dragover fires constantly during a drag and drop operation). Here's how I'm doing that:
var timeout;
function dragleaveFunctionality() {
// do stuff
}
function firefoxTimeoutHack() {
clearTimeout(timeout);
timeout = setTimeout(dragleaveFunctionality, 200);
}
$(document).on('dragover', firefoxTimeoutHack);
This code is essentially creating and clearing a timeout over and over again. The 200 millisecond timeout will not be reached unless the dragover event stops firing.
While this works, I don't like the idea of using a timeout for this purpose. It feels wrong. It also means there's a slight lag before the "dropzone" styling goes away.
The other idea I had was to detect when the mouse leaves the window, but the normal ways of doing that don't seem to work during drag and drop operations.
Does anyone out there have a better way of doing this?
UPDATE:
Here's the code I am using:
$(function() {
var counter = 0;
$(document).on('dragenter', function(e) {
counter += 1;
console.log(counter, e.target);
});
$(document).on('dragleave', function(e) {
counter -= 1;
console.log(counter, e.target);
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<p>Open up the console and look at what number is reporting when dragging files in and out of the window. The number should always be 0 when leaving the window, but in Firefox it's not.</p>
I've found a solution. The problem was not so much that the dragleave event wasn't firing; rather, the dragenter event was firing twice when first dragging a file into the window (and additionally sometimes when dragging over certain elements). My original solution was to use a counter to track when the final dragleave event was occuring, but the double firing of dragenter events was messing up the count. (Why couldn't I just listen for dragleave you ask? Well, because dragleave functions very similarly to mouseout in that it fires not only when leaving the element but also when entering a child element. Thus, when dragleave fires, your mouse may very well still be within the bounds of the original element.)
The solution I came up with was to keep track of which elements dragenter and dragleave had been triggered on. Since events propagate up to the document, listening for dragenter and dragleave on a particular element will capture not only events on that element but also events on its children.
So, I created a jQuery collection $() to keep track of what events were fired on what elements. I added the event.target to the collection whenever dragenter was fired, and I removed event.target from the collection whenever dragleave happened. The idea was that if the collection were empty it would mean I had actually left the original element because if I were entering a child element instead, at least one element (the child) would still be in the jQuery collection. Lastly, when the drop event is fired, I want to reset the collection to empty, so it's ready to go when the next dragenter event occurs.
jQuery also saves a lot of extra work because it automatically does duplicate checking, so event.target doesn't get added twice, even when Firefox was incorrectly double-invoking dragenter.
Phew, anyway, here's a basic version of the code I ended up using. I've put it into a simple jQuery plugin if anyone else is interested in using it. Basically, you call .draghover on any element, and draghoverstart is triggered when first dragging into the element, and draghoverend is triggered once the drag has actually left it.
// The plugin code
$.fn.draghover = function(options) {
return this.each(function() {
var collection = $(),
self = $(this);
self.on('dragenter', function(e) {
if (collection.length === 0) {
self.trigger('draghoverstart');
}
collection = collection.add(e.target);
});
self.on('dragleave drop', function(e) {
collection = collection.not(e.target);
if (collection.length === 0) {
self.trigger('draghoverend');
}
});
});
};
// Now that we have a plugin, we can listen for the new events
$(window).draghover().on({
'draghoverstart': function() {
console.log('A file has been dragged into the window.');
},
'draghoverend': function() {
console.log('A file has been dragged out of window.');
}
});
Without jQuery
To handle this without jQuery you can do something like this:
// I want to handle drag leaving on the document
let count = 0
onDragEnter = (event) => {
if (event.currentTarget === document) {
count += 1
}
}
onDragLeave = (event) => {
if (event.currentTarget === document) {
count += 0
}
if (count === 0) {
// Handle drag leave.
}
}
Depending on what you wish to accomplish you can get around this issue by using the :-moz-drag-over pseudo-class that is only available in Firefox which lets you react to a file being dragged over an element.
Take a look at this simple demo http://codepen.io/ryanseddon/pen/Ccsua
.dragover {
background: red;
width: 500px;
height: 300px;
}
.dragover:-moz-drag-over {
background: green;
}
Inspired by #PhilipWalton 's code, I simplified the jQuery plugin code.
$.fn.draghover = function(fnIn, fnOut) {
return this.each(function() {
var n = 0;
$(this).on('dragenter', function(e) {
(++n, n==1) && fnIn && fnIn.call(this, e);
}).on('dragleave drop', function(e) {
(--n, n==0) && fnOut && fnOut.call(this, e);
});
});
};
Now you can use the jquery plugin like jquery hover method:
// Testing code 1
$(window).draghover(function() {
console.log('into window');
}, function() {
console.log('out of window');
});
// Testing code 2
$('#d1').draghover(function() {
console.log('into #d1');
}, function() {
console.log('out of #d1');
});
only solution that has worked for me and took me a few goes hope this helps someone!
note when cloning you need to deepclone with events and data:
HTML:
<div class="dropbox"><p>Child element still works!</p></div>
<div class="dropbox"></div>
<div class="dropbox"></div>
jQuery
$('.dropbox').each(function(idx, el){
$(this).data("counter" , 0);
});
$('.dropbox').clone(true,true).appendTo($('body');
$('dropbox').on({
dragenter : function(e){
$(this).data().counter++;
<!-- YOUR CODE HERE -->
},
dragleave: function(e){
$(this).data().counter--;
if($(this).data().counter === 0)
<!-- THEN RUN YOUR CODE HERE -->
}
});
addEvent(document, "mouseout", function(e) {
e = e ? e : window.event;
var from = e.relatedTarget || e.toElement;
if (!from || from.nodeName == "HTML") {
// stop your drag event here
// for now we can just use an alert
alert("left window");
}
});
This is copied from How can I detect when the mouse leaves the window?. addEvent is just crossbrowser addEventListener.

Route events from one dom node to another WITHOUT JQUERY

My question is totally like: How do I pass javascript events from one element to another? except for the fact that I need a raw JS solution.
I've got a webos app whose UI features a layering of elements that scroll in conjunction with eachother on a page. Basically I have what amounts to an iframe (not quite, but in principle), and a floating header that lives in a z-layer above it. When I scroll the elements in the iframe, it also moves the floating header up.
However, I also need to scroll the underlying doc when the header is dragged.
This is a touchscreen interface, so I'm trying onmousemove and ontouchmove events.
I've got the following code, but it doesn't seem to do anything:
setupScrollFromHeader: function setupScrollFromHeader() {
// webos enyo stuff. Don't worry about it. just know that I get the
// raw dom elements through the this.$.elem.node syntax
var body = this.$.body, header = this.$.mailHeaderUnit;
if (!header.hasNode() && !body.hasNode()) {
return;
}
body = body.node;
// end enyo specific stuff
header.node.addEventListener('touchmove', function(event) {
console.log("### touch move");
event.preventDefault();
body.dispatchEvent(event);
var touch = event.touches[0];
console.log("Touch x:" + touch.pageX + ", y:" + touch.pageY);
}, true);
console.log("### set this stuff up");
}
I'm using dispatchEvent to forward the event, per:
https://developer.mozilla.org/en/DOM/element.dispatchEvent
I've tried this with either touchmove and mousemove events by themselves, toggling prevent default, and also changing the bubbling behavior with the true/false flags.
In all cases I see the log print out, but the events are never passed to the underlying element. What am I doing wrong? Is it even possible to pass the events around this way?
So this is the right way to route events. Looks like the widget I'm talking to needed a mousedown event before receiving the touchmove events. For maximum compatibility, I added listeners for both mouse and touch, for testing in browser and on device.
I came up with the following:
setupScrollFromHeader: function setupScrollFromHeader() {
if (setupScrollFromHeader.complete) {
return;
}
var body = this.$.body, header = this.$.mailHeaderUnit;
if (!header.hasNode() && !body.hasNode()) {
return;
}
var header = header.node;
var forwarder = function forwarder(event) {
body.$.view.node.dispatchEvent(event);
};
['mousedown', 'mousemove', 'touchstart', 'touchmove', 'touchend'].forEach(function(key) {
header.addEventListener(key, forwarder, true);
});
setupScrollFromHeader.complete = true;
},
In the general browser case, you can test such forwarding with with two buttons, routing the click event from one to the other works as expected through dispatchEvent(...).
ie:
var button1 = document.getElementById('button1');
var button2 = document.getElementById('button2');
button1.addEventListener('click', function(event) {
button2.dispatchEvent(event);
}, true);
button2.addEventListener('click', function(event) {
alert("Magnets. How do they work?");
}, true);
clicking button1 will fire the handler of button2.

iOS Web App touch gestures

I've searched all across the web to find a simple way of adding touch gestures to a simple button. Basically I'm trying to find a simple way of getting the back button (which you usually see on the task-bar at the top of an iOS device) to change CSS classes from 'normal' state to 'pressed' state when pressed.
Although I'm very new to Javascript, I would prefer to use standard DOM methods rather than jQuery (or any other library). Would anyone have some complete code and explain how the JavaScript code reads an ontouchstart and ontouchend event and how these functions could be used to change CSS classes?
Any help would be greatly appreciated!
TC
ontouchstart, ontouchmove and ontouchend are managed the same as onclick, onmousemove and so.
You can apply the listeners in a <script> tag or directly in the html element.
Using JavaScript only
var back = document.getElementById("back-button-id");
back.ontouchstart = function( event ) {
// using the target property of the event
// you can reach the hitted html element
event.target.className = 'css-href-selected-class-name';
}
back.ontouchend = function( event ) {
event.target.className = 'css-href-normal-class-name';
}
Using HTML tag and callbacks
1) Declare your Javascript callbacks to swap a css class for any state
function onclickCallback( event ) {
// do something
}
function ontouchstartCallback( event ) {
event.target.className = 'selected';
}
function ontouchendCallback( event ) {
event.target.className = 'normal';
}
2) Put the callbacks into the anchor tag (I suggest to use DIV instead of A)
<div class="normal" onclick="onclickCallback( event );" ontouchstart="ontouchstartCallback( event );" ontouchend="ontouchendCallback( event );">Back</div>
Edit 1: to prevent hilight freezing during scrolling
Try to add the ontouchmove handler
ontouchmove="ontouchmoveCallback( event );"
Then declare the handler function that swap the css class
function ontouchmoveCallback( event ) {
event.target.className = 'normal';
}
Hope this helps!
Ciao.
This should get you started:
HTML:
<input type="button" id="thebutton" value="Do Stuff!" />
Javascript:
var thebutton = document.getElementById("thebutton");
thebutton.ontouchstart = function(e)
{
this.setAttribute('class', 'pressed');
var touches = e.touches; // array of all touch data
var target = touches[0].target; // what DOM element was touched
var pageX = touches[0].pageX; // coords relative to site
var pageY = touches[0].pageY;
var clientX = touches[0].clientX; // coords relative to screen
var clientY = touches[0].clientY;
};
thebutton.ontouchmove = function(e)
{
var touches = e.touches; // same fields as above
var changedTouches = e.changedTouches; // only touches which have changed
};
thebutton.ontouchend = function(e)
{
this.setAttribute('class', '');
// cleanup, if needed
};
For more details, see: http://sitepen.com/blog/2008/07/10/touching-and-gesturing-on-the-iphone/
It's worth noting that MobileSafari sometimes does wonky things with touch events and form elements (input boxes in particular). You may find it's better to use a styled div than an actual input button.
EDIT: For what you're trying to do, I think you might be better served with simple click events, which generally work fine for things like button presses. Touch events are more for drag and drop, precise finger tracking etc. Try this:
thebutton.onclick = function(e) { this.setAttribute('class', 'your_class'); };
EDIT2: Now I see what you're asking for. Easiest way is this:
thebutton.ontouchstart = function(e) { this.setAttribute('class', 'pressed'); };
thebutton.ontouchend = function(e) { this.setAttribute('class', ''); };
There are a couple of libraries already for jQuery
http://plugins.jquery.com/project/multiswipe
And you also can check this demo from
http://taitems.github.com/Mobile-Web-based-Gesture-Recognition/
And you can fork the example and start working with it.
There are some options but everything its quite new.

Categories