Hi guys i am working on drag and drop event in android via jquery mobile. I tested the code on browser works fine but not on device. can anybody help me out this issue. I am following 1st tutorial of the link....
http://www.elated.com/articles/drag-and-drop-with-jquery-your-essential-guide/
The problem can be one of the followings:
1- the device has to have internet connection
2- the files you used are not "jquery mobile". they are just jquery files that are used to develop web pages.
3- If you use the application on a tablet, I guess your application can work by the mouse of tablet. However it can't work by touching.
These are the problems that I can guess. I hope you find the exact solution. And if you find it, please post it here for me :)
This is my script i have done Emrullah...
<script type="text/javascript">
$(document).ready(function() {
$( init );
function init() {
document.addEventListener("touchstart", touchHandler, true);
document.addEventListener("touchmove", touchHandler, true);
document.addEventListener("touchend", touchHandler, true);
document.addEventListener("touchcancel", touchHandler, true);
}
$(function(){
$(".drag")
.bind( "dragstart", function( event ){
// ref the "dragged" element, make a copy
var $drag = $( this ), $proxy = $drag.clone();
// modify the "dragged" source element
$drag.addClass("outline");
// insert and return the "proxy" element
return $proxy.appendTo( document.body ).addClass("ghost");
})
.bind( "drag", function( event ){
// update the "proxy" element position
$( event.dragProxy ).css({
left: event.offsetX,
top: event.offsetY
});
})
.bind( "dragend", function( event ){
// remove the "proxy" element
$( event.dragProxy ).fadeOut( "normal", function(){
$( this ).remove();
});
// if there is no drop AND the target was previously dropped
if ( !event.dropTarget && $(this).parent().is(".drop") ){
// output details of the action
$('#log').append('<div>Removed <b>'+ this.title +'</b> from <b>'+
this.parentNode.title +'</b></div>');
// put it in it's original <div>
$('#nodrop').append( this );
}
// restore to a normal state
$( this ).removeClass("outline");
});
$('.drop')
.bind( "dropstart", function( event ){
// don't drop in itself
if ( this == event.dragTarget.parentNode ) return false;
// activate the "drop" target element
$( this ).addClass("active");
})
.bind( "drop", function( event ){
// if there was a drop, move some data...
$( this ).append( event.dragTarget );
// output details of the action...
$('#log').append('<div>Dropped <b>'+ event.dragTarget.title +'</b> into <b>'+
this.title +'</b></div>');
})
.bind( "dropend", function( event ){
// deactivate the "drop" target element
$( this ).removeClass("active");
});
});
function touchHandler(event)
{
var touches = event.changedTouches,
first = touches[0],
type = "";
switch(event.type)
{
case "touchstart": type = "mousedown"; break;
case "touchmove": type="mousemove"; break;
case "touchend": type="mouseup"; break;
default: return;
}
var simulatedEvent = document.createEvent("MouseEvent");
simulatedEvent.initMouseEvent(type, true, true, window, 1,
first.screenX, first.screenY,
first.clientX, first.clientY, false,
false, false, false, 0/*left*/, null);
first.target.dispatchEvent(simulatedEvent);
event.preventDefault();
return;
}
});
</script>
Your code looks fine and you told that it had worked on browser successfully. I think the problem is possibly the jquery file that you used. If you had linked the jquery file that resides on a web site, make sure your device has internet connection. If no internet connection, download and put the "jquery mobile" file into the assest/www folder and link the file.
Didn't you run the application on an emulator? What is the error you faced?
Related
I searched a lot, but I couldn't find an answer. I use Intel XDK for Cordova/Phonegap development.
Everything is ok (emulate tabs, debug, etc.). I went to Build tab and get my .apk, moved it to SD card and installed, but, it doesn't work when run.
If I build my source with Phonegap Build (Online), everything works fine.
My JS code:
<script type="text/javascript">
document.addEventListener("backbutton", function(){ return; }, true);
document.addEventListener("deviceready", onDeviceReady, false);
function onDeviceReady()
{
//navigator.splashscreen.hide();
var server = 'http://xxxxxx/index.php?';
var user_uuid = device.uuid;
$( document ).ready
(
function()
{
$("#main_content").css("top", "50%");
$("#main_content").css("margin-top", "-"+($("#main_content").height()/2)+"px");
$("#main_content").show();
$("#big_img_load").attr("src", "img/ajax-loader.gif");
var xinv = setInterval
(
function()
{
var networkState = navigator.connection.type;
if(networkState.trim() == 'none')
$("#no_internet").show();
else
{
$.post
(
server+"do=boot",{useruuid: user_uuid},function(data)
{
if(data.trim() != "ok")
window.location = "error.html";
else
{
clearInterval(xinv);
window.location = "app.html";
}
}
);
}
},
1000
);
}
);
};
</script>
It remains in loading: No internet check, no POST to the URL, nothing.
Where is the problem? Why only build from XDK is not working?
My suspicion is you do not have the domain whitelisting section in the build settings set correctly for your app. See this article for some hints: https://software.intel.com/en-us/articles/cordova-cli-412-domain-whitelisting-with-intel-xdk-for-ajax-and-launching-external-apps and make sure to build your app using Crosswalk, not Android, for best results on Android devices.
I copied my code from the following link. It's a workaround for Passing Data From an InAppBrowser back to the app.
blogs.telerik.com/appbuilder/posts/13-12-23/cross-window-communication-with-cordova's-inappbrowser
The problem is that after each executescript() the Keyboard disappears.
This issue status here is "won't fix". So I'm wondering if there is an alternative solution. I only see a reference to KitKat users, but that would only represent a limited amount.
https://issues.apache.org/jira/browse/CB-5449
Suggestions?
setName: function() {
var win = window.open( "http://jsfiddle.net/tj_vantoll/K2yqc/show", "_blank",
"EnableViewPortScale=yes" );
win.addEventListener( "loadstop", function() {
win.executeScript({ code: "localStorage.setItem( 'name', '' );" });
var loop = setInterval(function() {
win.executeScript(
{
code: "localStorage.getItem( 'name' )"
},
function( values ) {
var name = values[ 0 ];
if ( name ) {
clearInterval( loop );
win.close();
$( "h1" ).html( "Welcome " + name + "!" );
}
}
);
});
});
}
Depending on your use case, it might be a feasible workaround to check if the keyboard is currently visible and avoid calling executeScript in that case.
Try using the com.ionic.keyboard plugin to get cordova.plugins.Keyboard.isVisible and use that in your setInterval function.
I have developed android phonegap app.I have a appended the dynamic form contains 'input' and 'select' in the div.I need to get scrollbar for that div.So i used iScroll.js but its not working properly.While typing in the textbox suddenly scrollbar disappears.This problem occurring often.
Here is my code:
function loaded()
{
var myScroll = new iScroll('wrapper',
{
scrollbarClass: 'myScrollbar',
useTransform: false,
vScroll: true,
onBeforeScrollStart: function (e)
{
var target = e.target;
while (target.nodeType != 1) target = target.parentNode;
if (target.tagName != 'SELECT' && target.tagName != 'INPUT' && target.tagName != 'TEXTAREA')
e.preventDefault();
}
});
}
document.addEventListener('touchmove', function (e) { e.preventDefault(); }, false);
document.addEventListener('DOMContentLoaded', loaded, false);
Please kindly guide me.Thanks in Advance
so a couple of things that will be helpful -
define your myScroll variable outside of your loaded function that way you can access it anywhere.
also after your content has loaded call myScroll.refresh() and have at least a 1ms delay on it. little hack that goes a long way.
Here is a chunk of text inside a scrollable div.
I can scroll it with two fingers in Chrome for Mac. I can scroll it with one finger on my iPad. However, I can't find any way to scroll it in Chrome for Android.
Perhaps there's a work-around using the touch API?
Another quick fix for Chrome for Android (http://chris-barr.com/index.php/entry/scrolling_a_overflowauto_element_on_a_touch_screen_device/)
First create a function to check whether the it is a touch device...
function isTouchDevice(){
try {
document.createEvent("TouchEvent");
return true;
} catch(e) {
return false;
}
}
then function to make div scrollable
function touchScroll(id){
if( isTouchDevice() ){ //if touch events exist...
var el = document.getElementById(id);
var scrollStartPos = 0;
document.getElementById(id).addEventListener("touchstart", function(event){
scrollStartPos = this.scrollTop + event.touches[0].pageY;
event.preventDefault();
}, false);
document.getElementById(id).addEventListener("touchmove", function(event){
this.scrollTop = scrollStartPos - event.touches[0].pageY;
event.preventDefault();
},false);
}
}
... call the function passing the element id
touchScroll("divIdName");
While browsing through the bug reports on this issue, I found this JavaScript library that solves the problem using touch events. Also it is reportedly fixed in Honeycomb, so hopefully the fix will hit people as soon as they push builds of Ice Cream Sandwich.
All android versions before 3.0 are bugged with overflow:scroll or auto (bug info).
For thoses using jQuery here is a quick fix :
function touchScroll(selector){
var scrollStartPos = 0;
$(selector).live('touchstart', function(event) {
scrollStartPos = this.scrollTop + event.originalEvent.touches[0].pageY;
});
$(selector).live('touchmove', function(event) {
this.scrollTop = scrollStartPos - event.originalEvent.touches[0].pageY;
});
}
and then if using modernizr :
if (Modernizr.touch) {
touchScroll($('.myScrollableContent'))
}
but it's not ideal because all touch-able devices will have this.
If you use Phonegap you can do (somewhere after phonegap inited):
if (window.device && device.platform=="Android" && parseInt(device.version) < 3){
touchScroll($('.myScrollableContent'))
}
I am trying to program a very standard JS behavior for a link using an HREF
onClick handler, and I am facing a strange problem caused by what I believe to be focus/touch mode behavior on Android.
Sometimes when I click on the link, instead of executing the action, it simply becomes selected/focused, with either just a focus rectangle or even also with a filled focus rectangle (selected as opposed to just focused?).
The pseudo-code right now is
go
I have tried doing something like:
go
But I still get the same pesky problem some of the time.
Try enabling Javascript on the webview.
In the activity that holds the webview, try this...
WebView wv = (WebView) findViewById(R.id.webview);
wv.getSettings().setJavaScriptEnabled(true);
I was having he same problem, but figured out it was because I did not enabled Javascript.
Try getting rid of the href attribute and see if that helps. For example, this works when viewed with the WebView component:
<p><a onClick="whereami()">Update Location</a></p>
I wonder if it's related to the onclick -- am I correct to assume that every now and then clicking any link does not follow it? To me, this seems related to the way you touch the screen (or how this is interpreted), like maybe by clicking next to the link and dragging a bit, rather than clicking on the link?
(If my assumption is correct, then this might be faulty hardware: maybe you can try on another device? Or maybe it only happens on a particular side of the link if the screen is not aligned well, and then there might be some software offset one can change?)
Try inserting this "driver" into your page code, and let us know if it works . . . It seems to be working on my site which had the same problem:
//Mouse & Touch -> Consistent Click / Mouse Commands -> Useful driver
(function() {
var isTouch = false;
var simulated_flag = 'handler_simulated';
var touch_click_array = {};
const clickMoveThreshold = 20; //Pixels
function mouseHandler(event) {
if (isTouch) {
if (!event.hasOwnProperty(simulated_flag)) {
//Unreliable mouse commands - In my opinion
var fixed = new jQuery.Event(event);
fixed.preventDefault();
fixed.stopPropagation();
}
}
else {
//Mouse commands are consistent
//TODO: generate corresponding touches
}
}
function mouseFromTouch(type, touch) {
var event = document.createEvent("MouseEvent");
event.initMouseEvent(type, true, true, window, 1, touch.screenX, touch.screenY, touch.clientX, touch.clientY
, false, false, false, false, 0, null);
event[simulated_flag] = true;
touch.target.dispatchEvent(event);
};
function touchHandler(event) {
var touches = event.changedTouches
,first = touches[0]
,type = ""
;
if (!event.hasOwnProperty(simulated_flag)) {
isTouch = true;
//Simulate mouse commands
switch (event.type) {
case "touchstart":
for (var i = 0; i < touches.length; i++) {
var touch = touches[i];
touch_click_array[touch.identifier] = { x: touch.screenX, y: touch.screenY };
}
mouseFromTouch("mousedown", first);
break;
case "touchmove":
for (var i = 0; i < touches.length; i++) {
var touch = touches[i];
var id = touch.identifier;
var data = touch_click_array[id];
if (data !== undefined) {
if (Math.abs(data.x - touch.screenX) + Math.abs(data.y - touch.screenY) > clickMoveThreshold) {
delete touch_click_array[id];
}
}
}
mouseFromTouch("mousemove", first);
break;
case "touchcancel":
//Not sure what should happen here . . .
break;
case "touchend":
mouseFromTouch("mouseup", first);
for (var i = 0; i < touches.length; i++) {
var touch = touches[i];
if (touch_click_array.hasOwnProperty(touch.identifier)) {
mouseFromTouch("click", touch);
delete touch_click_array[touch.identifier];
}
}
break;
}
}
}
document.addEventListener("mousedown", mouseHandler, true);
document.addEventListener("mousemove", mouseHandler, true);
document.addEventListener("mouseup", mouseHandler, true);
document.addEventListener("click", mouseHandler, true);
document.addEventListener("touchstart", touchHandler, true);
document.addEventListener("touchmove", touchHandler, true);
document.addEventListener("touchcancel", touchHandler, true);
document.addEventListener("touchend", touchHandler, true);
})();
Now it isn't a 100% complete script - multi-touch would probably be a little wonky, and if you built an interface depending on touch commands, it doesn't generate those in this version. But, it fixed my link-clicking problem.
Erm - ps - it's using jQuery. If you need a non-jQuery version, you can probably just remove the new jQuery.Event from the mouseHandler() function (in other words, use the original event: var fixed = event;), and I believe most browsers would be ok. I am not exactly a js compatibility expert though.
PPS - Tested with Android 1.6
PPPS - Had to modify script to allow a threshold - actual devices were having some problems with a move event being fired during the press. Probably not ideal; if anyone wants to chime in on a better way for doing that, I'd be interested in hearing...
Recently I came across exactly the same problem. I was using the onclick on a button. Sometimes it did not execute the javascript at all. The thing that worked for me was that enable the javascript before loading a url in the webview
// Enable javascript
WebSettings webSettings = mWebView.getSettings();
webSettings.setJavaScriptEnabled(true);
// To bind javascript code to android
mWebView.addJavascriptInterface(new JavaScriptInterface(this), "Android");
mWebView.loadUrl(url);