How to detect user touch with phonegap using JS - javascript

I am using phonegap to build android apps.
I would like to detect the touch event from a user so I can pop-up an alert. However, how do I call the ontouch event from javascript?
Thanks!

Below is an example that shows touchstart and touchend. It demonstrates two different ways to attach touch events: element attributes or JavaScript's addEventListener.
Since it is listening for touch events, the events will not fire on a desktop browser (which supports mouse events). To test the page, you can open it a Android or iOS simulator.
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0;" />
<style type="text/css">
a {
color:black;
display:block;
margin:10px 0px;
}
</style>
<script type="text/javascript">
function onload() {
document.getElementById('touchstart').addEventListener('touchstart', hello, false);
document.getElementById('touchend').addEventListener('touchend', bye, false);
}
function hello() {
alert('hello');
}
function bye() {
alert('bye');
}
</script>
<title>Touch Example</title>
</head>
<body onload="onload();">
<h1>Touch</h1>
Attribute: ontouchstart
Attribute: ontouchend
addEventListener: touchstart
addEventListener: touchend
</body>
</html>

Related

Load event isn't working in Google chrome

So I'm just learning about load event handler and when I run the code in Google chrome it doesn't work can someone tell me why and how I can fix
it. By the way as u can see I want the alert function to execute as soon as everything is loaded thanks
This is my code below 👇
<!DOCTYPE HTML>
<html>
<head>
<title>Button</title>
<meta charset="utf-8">
<style>
body{
display:grid;
height:100vh;
}
h2{
margin:auto;
}
</style>
</head>
<body>
<h2>experiment</h2>
<script>
var exp =document.querySelector("h2");
function fun(){
alert("is it a success?");
}
exp.addEventListener("load", fun);
</script>
</body>
</html>
Use DOMContentLoaded instead
The DOMContentLoaded event will trigger earlier and is usually
considered the better option.
document.addEventListener('DOMContentLoaded', fun);
[the load event] should be used only to detect a fully-loaded page. It
is a common mistake to use load where DOMContentLoaded would be more
appropriate.
If you must use the load event
If you must use the load event, you can add a listener to window instead:
window.addEventListener('load', fun);

Jquery closing on parent click

I want a window to close only when pop_up is clicked (as opposed to clicking div contents). E.g. clicking the background layer hides the div. In the code below I don't want it to close #pop_up when clicking the div contents bot only on "pop_up".
How can I do this?
$("#pop_up").click(function() {
$("#pop_up").hide();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="pop_up">
<div id="pop_up_content">
<h1> world </h1>
</div>
</div>
What you are experiencing is the bubbling and capturing behaviour of events.
Check this answer What is event bubbling and capturing? .
The simples approach would be to attach a onClick to the child and stop the bubbling.
$("#pop_up_content").click(function(ev) {
ev.preventDefault()
ev.stopImmediatePropagation() // best to use to stop other event listeners from being called
});
You can use the event argument of the click, and see if the click is inside another element (or it is the element itself)
JSFiddle: https://jsfiddle.net/32mz2x3x/1/
$("#pop_up").click(function(event) {
if ($(event.target).parents().andSelf().is('#pop_up_content')) {
return
}
$("#pop_up").hide();
});
I have used parents to check if where you click is inside pop_up_content element, and I used andSelf because maybe you click on #pop_up_content (and not inside it)
More info:
jQuery andSelf function
jQuery is function
jQuery parents function
jQuery event object
use the form that allows a filter selector, combined with :not():
$("#pop_up").on('click', ':not(#pop_up_content)', function (e) {
$("#pop_up").hide();
});
JSBin: http://jsbin.com/hoyizos/edit?html,css,js,output
$("#pop_up").click(function(e) {
if ($(event.target).is($("#pop_up"))){
$("#pop_up").hide();
}
});
h1{
margin:50px 50px;
background-color:red;
display:inline;
}
#pop_up_content{
background-color:yellow;
}
#pop_up{
margin:10px;
background-color:green;
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
<script src="https://code.jquery.com/jquery-3.0.0.js"></script>
</head>
<body>
<div id="pop_up">
<div id="pop_up_content">pop_up_content
<h1> world </h1>
</div>
I am the pop_up!
</div>
</body>
</html>
Don't cancel event bubbling!: The Dangers of Stopping Event Propagation, use it only if there is no other way.
Don't use andSelf() if you plan to use jQuery 3.x, because it is deprecated since v1.8 and will be removed in jQuery v3.
Note: This function has been deprecated and is now an alias for
.addBack(), which should be used with jQuery 1.8 and later.
If you use jQuery 1.8 < use addBack instead.

Inline ckeditor and keypress event

I use inline Ckeditor to edit content. I want to bind a keypress event to the div i edit. I mean, i need an event that will fire when i change the content of div.
Here is an example of how i do that
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery/1.9.1/jquery.js"></script>
<script src="http://cdnjs.cloudflare.com/ajax/libs/ckeditor/4.2/ckeditor.js"></script>
</head>
<body>
<div id="ckediv" contenteditable="true">Editing with CKEDITOR</div>
<br>
<script type='text/javascript'>
$( "#ckediv" ).keypress(function() {
alert('cke key pressed');
});
</script>
</body>
</html>
The problem is that keypress is not fired in ie and chrome when i press enter ordelete keys. If i make a div with contenteditable="true" but without Ckeditor then the event works well.
Here is a jsfiddle with code that shows how it works now http://jsfiddle.net/uAc7c/4/ .I don't know why, but for some reason this jsfiddle(keypress event) doesn't work in ie. When i tested locally with above source, it worked.
And here is a jsfiddle without Ckeditor that shows how it should work http://jsfiddle.net/mPM4J/4/
JQuery Documentation says:
Note: as the keypress event isn't covered by any official specification, the actual behavior encountered when using it may differ across browsers, browser versions, and platforms.
So i guess IE and Chrome are two of the unsupported browsers.
Therefore try using the keyup event instead like this:
$( "#ckediv" ).keyup(function() {
alert('cke key pressed');
});
For more info, see here:
KeyUp Documentation in the JQuery API

HTML5 audio element doen't work on mobile

I have a sample with HTML5 element. I need dynamically create audio element after ajax request and play it. But it doesn't work on mobile! Android 4.1 and IOS7. It works perfect on desktop!
It doesn't work after page load. But it works after press buttom and after press button play on control. Why?
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Untitled Document</title>
<script>
function play() {
var audio = document.createElement('audio');
audio.autoplay = true;
audio.controls = true;
audio.src='http://s3.amazonaws.com/audiojs/02-juicy-r.mp3';
document.body.appendChild(audio);
audio.play();
}
setTimeout(play, 1000);
</script>
</head>
<body>
<h1>test</h1>
<input type='button' value='Press Me' onclick='play()' />
</body>
</html>
I had the same experience where audio wouldn't play after an AJAX call. I guess it has to do with security settings on mobile. Mobile browsers behave differently. The same happens when trying to call up the keyboard on mobile. It is only possible after a keypress or a click event but not automatically on page load or after an Ajax call.
One solution that I used might be to trigger the sound outside of the Ajax call, in the event that triggered the Ajax call in the first place.

iPhone/Android browser occasionally follows link href instead of jQuery onclick event

I have a mobile web gallery page where I have a CSS floated "next" link. The CSS float property causes the link to have a display: block behavior on it. A jQuery touchstart event is bound to the link. When the user clicks on the link, the Javascript code bound to that touchstart event advances the gallery by one slide via Ajax. In other words, there is no page refresh.
However, I noticed that occasionally when I touch an area of the link's block space that is not the link text itself, the browser follows the href and causes a page refresh (because the URL has changed) instead of executing the Javascript code bound to the touchstart event.
Has anybody seen this before? Is there a way to fix this?
I simplified it down to this code below, and it still happens, although much less frequently.
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0" />
<title>Test</title>
<script type='text/javascript' src='http://code.jquery.com/jquery-1.7.1.js'></script>
<style type='text/css'>
.cont { width: 320px; }
.next { border-left: 1px solid #000; float: right; text-align: right; width: 65px; }
.msg { clear: both; width: 200px; }
</style>
<script type='text/javascript'>//<![CDATA[
$(function(){
$('.next').bind('click touchstart', function(event) {
event.preventDefault();
if (event.type == 'touchstart') {
$(this).unbind('click');
}
$('.msg').append('<p>Click!</p>');
});
});//]]>
</script>
</head>
<body>
<div class="cont">Next</div>
<div class="msg"></div>
</body>
</html>
I tested this on my iPhone and it seems to work. For some reason after registering a touchstart event you are unbinding the click events. Is there any reason for that?
When you click on the text of the link all it seems to register is indeed touch start, so unbinding click does not break things. I do believe, however, that when you touch outside the text link, but still within the block space it registers both a touchstart and click, so at this point you have already unbound click and it works as a regular link.
You should notice, that on your first click outside the bounds it never goes to yahoo.com. It's only the subsequent once that do that.
So in essence what you need to do is remove that unbind, as so:
<script type='text/javascript'>//<![CDATA[
$(function(){
$('.next').bind('click touchstart', function(event) {
event.preventDefault();
$('.msg').append('<p>Click!</p>');
});
});//]]>
</script>
Is there any reason why you would want to unbind click?

Categories