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.
Related
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.
I'm trying to show/hide some of text in a button.
the button is
<button id="SOS" onmouseover="show()" onmouseout="hide();">
<p>S.O.S</p>
<div id="sos_left"> <?=$text_to_show_hide?></div>
</button>
and the javascript code is
<script type="text/javascript">
function show()
{
sos_left=document.getElementById('sos_left');
alert("mouseover");
sos_left.style.color = "red";
sos_left.style.fontSize = "28";
}
function hide(){
sos_left=document.getElementById('sos_left');
alert("mouseout");
sos_left.style.color = "blue";
sos_left.style.fontSize = "0";
}
</script>
the thing is that the mouse out alerts even when I'm mouse overing.
NOTE: I can't use jquery because the site is vbulletin based and I use this code on one of the templates.
The problem is that mouseover and mouseout events bubble up, and this means that when your cursor enters and exits from elements that are descendants of your button, the event listener defined on the button is triggered too.
What you can do is to check if the element that generated the event is actually the <button> element. Fix the DOM like this:
<button id="SOS" onmouseover="show(event)" onmouseout="hide(event);">...
Then your JS code:
function show(e) {
if ((e.target || e.srcElement).id !== "SOS") return;
...
function hide(e) {
var tgt = e.target || e.srcElement;
if (tgt.id !== "SOS") return;
// If the cursor enter in one of the descendants, mouseout is fired, but
// we don't want to handle this
if (tgt.contains) {
if (tgt.contains(e.relatedTarget || e.toElement)) return;
} else if (this.compareDocumentPosition)
if (tgt.compareDocumentPosition(e.relatedTarget)
& Node.DOCUMENT_POSITION_CONTAINS) return;
...
In Internet Explorer (and now in Opera too) there are these events mouseenter and mouseleave that behave very similarly, but don't bubble up. For other browsers they're emulated in common frameworks like jQuery.
On a final note, I'd suggest you to use some more modern method to attach your event listeners than the traditional one. Plus, the way you define sos_left implies that it becomes a global variable. Use the keyword var in front of the definition.
you dont hide anything..
use display:none to "remove" element, or visibility:hidden to hide element.
to "re-add" the element, use display: block or visibility:visible, if you used visibility attribute to hide.
try each both to see the difference.
another problem is,
you try to use sos_left as variable, but you didn't declare it as variable.
use var sos_left instead of.
That's because you apply the event to the div not the button. Try this:
sos_button=document.getElementById('SOS');
I am adding a custom data attribute data-js-href to various HTML elements, and these elements should behave just like a link when clicked. If a link within such an element is clicked, the link should take precedence and the data-js-href functionality should be ignored, though. Furthermore, the solution also needs to work with elements that are dynamically added at a later time.
So far, I have come up with the following solution. It basically checks if the click was performed on a link, or any child element of a link (think <a href='…'><img src='…' alt='…' /></a>).
// Make all elements with a `data-js-href` attribute clickable
$$('body').addEvent('click:relay([data-js-href])',
function(event, clicked) {
var link = clicked.get('data-js-href');
if (link && !event.target.match('a')) {
var parents = event.target.getParents();
for (var i = 0; i < parents.length && parents[i] != clicked; i++) {
if (parents[i].match('a')) {
return;
}
}
document.location.href = link;
}
});
It works, but it feels very clumsy, and I think that there has to be a more elegant solution. I tried something along the lines of
$$('body').addEvent('click:relay([data-js-href] a)',
function(event, clicked) {
event.stopPropagation();
}
but to no avail. (I littered the code with some console.log() messages to verify the behavior.) Any idea is welcome.
you can do this with 2 delegated events - no reverse lookups and it's cheap as they will share the same event. the downside is, it is the same event so it will fire for both and there's no stopping it via the event methods (already bubbled, it's a single event that stacks up multiple pseudo event callbacks and executes them in order--the event has stopped but the callbacks continue) That's perhaps an inconsistency in mootools event vs delegation implementation but it's a subject of another issue.
Workarounds for now can be:
to have the 2 event handlers communicate through each other. It will scale and work with any new els added.
to add the delegators on 2 different elements. eg. document.body and #mainWrap.
http://jsfiddle.net/dimitar/J59PD/4/
var showURL = function(howLong) {
// debug.
return function() {
console.log(window.location.href);
}.delay(howLong || 1000);
};
document.id(document.body).addEvents({
"click:relay([data-js-href] a))": function(e) {
// performance on lookup for repeat clicks.
var parent = this.retrieve("parent");
if (!parent) {
parent = this.getParent("[data-js-href]");
this.store("parent", parent);
}
// communicate it's a dummy event to parent delegator.
parent.store("linkEvent", e);
// let it bubble...
},
"click:relay([data-js-href])": function(e) {
// show where we have gone.
showURL(1500);
if (this.retrieve("linkEvent")) {
this.eliminate("linkEvent");
return;
}
var prop = this.get("data-js-href");
if (prop)
window.location.href = prop;
}
});
Discussed this with Ibolmo and Keeto from the mootools team on IRC as well when my initial attempt failed to work and both callbacks fired despite the event.stop: http://jsfiddle.net/dimitar/J59PD/
As a result, there was briefly a ticket open on the mootools github issues: https://github.com/mootools/mootools-core/issues/2105 but it then went into a discussion of what the right thing to do from the library standpoint is and how viable it is to pursue changing the way things work so...
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.
My absolutely positioned canvas elements are blocking all the mouse events so that nothing underneath them can be clicked, same problem mentioned here and here.
I have multiple canvas layers that need to be at specific z-index's so I need to forward mouse events through the canvases. pointer-events: none; works in good browsers, but for IE9 I need javascript to do it, here is my current solution,
var evts = [ 'click', 'mousedown', 'mouseup', 'dblclick'],
canvases = $('canvas');
$.each(evts, function(_, event){
canvases.bind(event, function(evt){
var target,
pEvent;
$(this).hide();
target = document.elementFromPoint(evt.clientX, evt.clientY);
$(this).show();
pEvent = $.Event(event);
pEvent.target = target;
pEvent.data = evt.data;
pEvent.currentTarget = target;
pEvent.pageX = evt.pageX;
pEvent.pageY = evt.pageY;
pEvent.result = evt.result;
pEvent.timeStamp = evt.timeStamp;
pEvent.which = evt.which;
$(target).trigger(event, pEvent);
});
});
Working example,
jsFiddle
Questions;
1. I'm creating the new event and passing over the relevant data, would it be safe to pass the evt var with the target and currentTarget modified?
2. How can I propogate a right click?
Or does anyone have a better way to accomplish this? The other related questions are quite old.
There's no clean way to pass the events cross-browser. You can pass the (modified) event on but you can't guarantee that it will work as it might have naturally, especially cross-browser.
For right click using your code just do this: http://jsfiddle.net/6WMXh/20/
(you half used the jquery extra info part but never did anything with it)