JQuery Mobile ListView - android

I'm having 2 strange problems with the code I'm using to pull in some data to use in a listview. Here is my javascript:
function getOrders(status, url) {
$(function () {
//check if url from pagination
if (!url) {
url = api_url + '/orders/?callback=?&status=' + status;
} else {
url = root_url + url + '&callback=?';
}
$.mobile.loading('show');
$.getJSON(url, null, function (d) {
//declare a variable with which to build our output (it's best to buffer output and only do one append at the end since DOM manipulation is CPU expensive)
var output = '';
//iterate through the data (we could also get rid of the jQuery here by using `for (key in data) {
$.each(d.objects, function (index, value) {
output += '<li><a id="' + value.reference + '" href="view_order.html" class="view_order"><h3>' + value.reference + ' - ' + value.client.company + '</h3><p>' + value.order_date + ' ' + value.user.username + '</p></a></li>';
});
$('#orders_list').html(output).listview('refresh');
//if paginated, update next button
if (d.meta.next) {
$("#id_ordersNext").attr('href', d.meta.next);
$("#id_ordersNext").show();
} else {
$("#id_ordersNext").hide();
}
if (d.meta.previous) {
$("#id_ordersPrevious").attr('href', d.meta.previous);
$("#id_ordersPrevious").show();
} else {
$("#id_ordersPrevious").hide();
}
$("#id_ordersTotal").html(d.meta.total_count);
$.mobile.loading('hide');
});
});
}
$(function () {
//bind the nav
$(".order_nav").die();
$(".order_nav").live('click', function () {
$(".order_nav").each(function () {
$(this).removeClass('ui-btn-active');
});
$(this).addClass('ui-btn-active');
getOrders($(this).attr('href'));
return false;
});
//bind the view order
$(".view_order").die();
$(".view_order").live('click', function () {
//save var
window.viewOrderReference = $(this).attr('id');
$.mobile.changePage("view_order.html");
});
$("#id_ordersNext,#id_ordersPrevious").die();
$("#id_ordersNext,#id_ordersPrevious").live('click', function () {
getOrders(null, $(this).attr('href'));
return false;
});
//default view
getOrders('Order Placed');
});
Here is the html I'm using for the page that's being loaded via JQMobile:
<div data-role="page" data-needs-auth='true'>
<script src="js/list_orders.js"></script>
<div class="headerDiv" data-role='header' data-theme='b'>Home
<h1>Jubilee Distributors</h1>
Login</div>
<div data-role='navbar'>
<ul>
<li>Placed</li>
<li>Picked</li>
<li>Delivered</li>
</ul>
</div>
<div data-role="content">
<ul data-role='listview' id="orders_list" data-filter="true"><li>No records found</li></ul>
<p>Previous <span id='id_ordersTotal' class='record-count'></span> records found Previous
</p>
</div>
<div id='footerDiv' data-role="footer"></div>
</div>
This all works fine in any browser on a desktop, but when I run it on an Android device 2 things happen, or rather don't.
The last line in the $(function() - getOrders('Order Placed'), doesn't seem to execute, or if it does, it's not updating the list with the returned result. If I click the first link with the "Orders Placed" it works no probs.
The addClass is not actually adding the class.
Like I said, this all works fine in any desktop browser, but not on the Android device.
Any ideas?
EDIT: Fixed the second problem, however the first problem still exists.. It works if I navigate to the page, then away from it, then back again tho.

Fixed this error by changing the dom ready function to pageinit.

Related

Using jQuery "swipe" function to navigate an array of images

I'm building a simple slideshow that is controlled by buttons when viewed on a computer and by swiping gestures on touch screen devices. This is a demo with 3 images.
Each image, its corresponding caption and the navigation are contained within one div. Here's the first one:
<div class="item" id="1">
<img src="...">
<div class="caption">
caption 1
</div>
<div class="navigation">
&lt 1 / 3 &gt
</div>
</div>
These divs are shown or hidden using the "click" and "swipeleft / swiperight" functions.
$(document).ready(function () {
$("#1prev").click(function () {
$("#1").hide();
$("#3").show();
});
$("#1").on("swipeleft", function () {
$("#1").hide();
$("#3").show();
});
$("#1next").click(function () {
$("#1").hide();
$("#2").show();
});
$("#1").on("swiperight", function () {
$("#1").hide();
$("#2").show();
});
});
The slideshow will contain as many as 40 images in total. Is there a way to condense the script? Is this a relatively efficient and accessible solution? Is the code written properly? Can it be improved?
You could do something like this:
For the items, I have assigned classes to the prev and next buttons instead of IDs.
<div class="item" id="1">
<img src="http://www.leecorbin.co/img1.jpg" width="50%" />
<div class="caption">caption 1</div>
<div class="navigation">
&lt
1 / 3
&gt
</div>
</div>
Then in script, on pagecreate
Hide all items and show only the first one.
Add a handler for swipeleft and swiperight on items.
Add a click handler for the navigation buttons
Within these handlers determine which direction we are going and which slide we are currently on.
Call a function passing in the direction and current slide; it determines the next slide to show and makes the transition.
$(document).on("pagecreate", "#page1", function () {
$(".item").hide().first(0).show();
$(document).on("swipeleft swiperight", ".item", function (e) {
var dir = 'prev';
if (e.type == 'swipeleft') {
dir = 'next';
}
GoToNextSlide($(this), dir);
});
$(document).on("click", ".navigation > a", function (e) {
var dir = 'prev';
if ($(this).hasClass("nextBtn")) {
dir = 'next';
}
var $item = $(this).closest(".item");
GoToNextSlide($item, dir);
});
});
function GoToNextSlide($item, direction) {
var $next;
if (direction == 'next') {
if ($item.next().length > 0) {
$next = $item.next();
} else {
$next = $(".item").first();
}
} else {
if ($item.prev().length > 0) {
$next = $item.prev();
} else {
$next = $(".item").last();
}
}
$item.fadeOut(function () {
$next.fadeIn();
});
}
Updated DEMO

load my facebook username and picture in HTML Page

I m developing and android application using phonegap . I m follwing this tutorial https://github.com/phonegap-build/FacebookConnect/tree/962eb0a1c07935ff813e28aa9eaa5581f2e10416 and i m succesfully connecting to facebook in Phonegap and i m displaying my Facebook username and Picture in my (Index.html) and sending my informations to the server.
In this page (index.html) , i have a button that let me go to another HTML Page(Profile.html). I m trying to display my facebook informations to this page (Profile.html) as well as the (Index.html)
Here is the code in my JS File that let me display my informations after a connect to facebook in my Indx.HTML Page and let me also send these informations to the server:
function handleStatusChange(session)
{
console.log('Got the user\'s session: ' + JSON.stringify(session));
alert('Got the user\'s session: ' + JSON.stringify(session));
if (session.authResponse)
{
//document.body.className = 'connected';
//Fetch user's id, name, and picture
FB.api('/me',
{
fields: 'name, picture,first_name,last_name,email'
},
function(response)
{
if (!response.error)
{
document.body.className = 'connected';
user = response;
console.log('Got the user\'s name and picture: ' + JSON.stringify(response));
console.log('FB name, ' + response.name);
console.log(('FB picture, ' + response.picture.data.url));
// alert('Fb Id,'+response.id);
//alert('Email'+response.email);
// alert('FB Last name'+response.first_name);
// alert('FB name, ' + response.last_name);
//Update display of user name and picture
if (document.getElementById('user-name'))
{
document.getElementById('user-name').innerHTML = user.name;
}
if (document.getElementById('user-picture'))
{
document.getElementById('user-picture').src = user.picture.data.url;
}
var callDataLogin = JSON.stringify({'serviceName':"global_functions", 'methodName':'login',"parameters":[response.id,response.last_name,response.first_name,response.email]});
$.post('Server URL', callDataLogin, function(resp){}).done(function(data)
{
console.log(data);
//alert(data);
//alert(" Send User Facebook info to server , Login");
});
}
else
{
document.body.className = 'not_connected';
console.log('Error getting user info: ' + JSON.stringify(response.error));
if (response.error.error_subcode && response.error.error_subcode == "458")
{
setTimeout(function()
{
alert("The app was removed. Please log in again.");
}, 0);
}
logout();
}
clearAction();
});
}
else {
document.body.className = 'not_connected';
clearAction();
}
}
And here is the code in my Index.html page that let me display my Facebook User Informations:
<div id="page-root" class="page">
<div class="show_when_connected">
<div id="welcome"><img id="user-picture" /><br /><span id="user-name"></span></div>
</div>
I also add this code to my Profile.html Page to display my facebook User Informations
<div id="page-root" class="page">
<div class="show_when_connected">
<div id="welcome"><img id="user-picture" /><br /><span id="user-name"></span></div>
</div>
But it s not displaying anything in my Profile.html as in my Index.html
Thanks for your help
////////////////////////////////////////UPDATE/////////////////////////////////////////////
in my js file here is the code that i put
<script>
//get the id
var getFbId=sessionStorage.getItem('Fbid');
//set the id html
document.getElementById('idget').innerHTML =getFbId;
var getFbName=sessionStorage.getItem('FBName');
//set the Name html
document.getElementById('Nameget').innerHTML =getFbName;
var getFbPicture=sessionStorage.getItem('FBPicture');
//set the Picture html
document.getElementById('Pictureget').innerHTML =getFbPicture;
</script>
and in my Profile.html here is the code that i used:
<div id="idget"></div>
<div id="Nameget"></div>
<img id="Pictureget">
You just set your fb credentials in localstorage/session storage after this you can retrieve in any page that you want.
function(response)
{
if (!response.error)
{
document.body.className = 'connected';
user = response;
console.log('Got the user\'s name and picture: ' + JSON.stringify(response));
console.log('FB name, ' + response.name);
console.log(('FB picture, ' + response.picture.data.url));
//set the id in session storage/localstorage
sessionStorage.setItem('Fbid',response.id);
//For localstorage
window.localStorage.setItem( 'Fbid', response.id);
}
}
For get this value in another html page by this way
//get the id from session
var getFbId=sessionStorage.getItem('Fbid');
//get the id from localstorage
var fromLocalStorage=window.localStorage.getItem( 'Fbid' );
//set the id html
document.getElementById('idget').innerHTML =getFbid;

Jquery Mobile Global Popup Background

i got a problem with my app.i'm developing an app with cordova & jquery mobile.
Following the code on jquery mobile master i found that code
function openPopup(idPopup, onTimeout) {
var popupContent = '<div data-role="content" data-theme="a" style="border:0px;" class="ui-corner-bottom ui-content centerContent">' +
'<h3 class="ui-title" id="myTitle">Caricamento</h3>' +
'<img src="img/load_shop33sell.gif"/></div>';
var popup = '<div data-role="popup" id="popup-' + idPopup + '" data-overlay-theme="b" data-theme="a" class="ui-content">' + popupContent + '</div>';
$.mobile.activePage.append(popup).trigger("pagecreate");
$("#popup-" + idPopup).on({
popupbeforeposition: function () {
$('.ui-popup-screen').off();
}
});
var fallback = setTimeout(function () {
$("#popup-" + idPopup).popup("open");
}, 3000);
$("#popup-" + idPopup).popup("open");
clearTimeout(fallback);
callback = setTimeout(function () {
$("#popup-" + idPopup).popup('close');
if (onTimeout && typeof (onTimeout) === "function") {
onTimeout();
}
}, 20000);
}
With this code, i am able to open a popup without needing to include a
<div data-role="popup">..../<div>
in each page i create.I just modified a bit adding the popupbeforeposition event to make the popup undismissable by clicking on the background.
Well, it works fine but i got a problem. Randomly in my first page this happens
Seems like the popup opens before it get the right position. In addition i have a second page which is scrollable, and i always have this situation. If i try to scroll up to the top of the page, i have half of the screen black, as in first picture.
What could be the problem?
Thanks in advance, and sorry for my english :)
As you mentioned it is due to data-overlay-theme="a". But actually it should works in good way..thinking that this is due to $('.ui-popup-screen').off();
you can observe here
Prevent JQuery Mobile from closing a popup when user taps outside of it
if you need an alternative way for black background you can do this ..
Add div <div id="overlaypage"></div> like this inside <div data-role="page">
HTML:
<div data-role="page">
<div id="overlaypage"></div>
<div id="header"></div>
</div>
CSS:
.overlaycont {
background:#000;
bottom:0;
left:0;
position:fixed;
right:0;
top:0;
z-index:100;
opacity:.6
}
jQuery:
When you try to click to open a popup addclass
$("#overlaypage").addClass("overlaycont");
When you closing the popup remove class
$("#overlaypage").removeClass("overlaycont");
Working demo: http://jsfiddle.net/nPeaV/7421/
ok, i solved the problem combining the two answers, this is my function to open popup
function apriPopup(idPopup, onTimeout) {
$(".ui-navbar").css('display','none');
var popupContent = '<div data-role="content" data-theme="a" style="border:0px;" class="ui-corner-bottom ui-content centerContent">' +
'<h3 class="ui-title" id="myTitle">Caricamento</h3>' +
'<img src="img/load_shop33sell.gif"/></div>';
var popup = '<div data-role="popup" data-dismissible="false" id="popup-' + idPopup + '" data-theme="a" class="ui-content">' + popupContent + '</div>';
$.mobile.activePage.append(popup).trigger("create");
//$("#popup-" + idPopup).on({
// popupbeforeposition: function () {
// $('.ui-popup-screen').off();
// }
//});
var fallback = setTimeout(function () {
$("#overlaypage").addClass("overlaycont");
$("#popup-" + idPopup).popup("open");
}, 3000);
$("#overlaypage").addClass("overlaycont");
$("#popup-" + idPopup).popup("open");
clearTimeout(fallback);
callback = setTimeout(function () {
$(".ui-navbar").css('display','block');
$("#overlaypage").removeClass("overlaycont");
$("#popup-" + idPopup).popup('close');
if (onTimeout && typeof (onTimeout) === "function") {
onTimeout();
}
}, 20000);
}
as you can see i have commentend the $('.ui-popup-screen').off(); , added a data-dismissable="false"
and i have used the overlaycont css style suggested by dileep.
in my index, as child of body,i added a <div id="overlaypage"></div> and $("#overlaypage").addClass("overlaycont");,
in this way popup is undismissabile by cliking outside of it, and background is displayed correctly.
such a pain!

PhoneGap Conversion - HTML to .apk

I am turning a HTML app into a .apk using https://build.phonegap.com and everything works great appart from my file selector.
<input name="file" type="file" id="file">
I want to be able to select images only (it doesnt matter if it can select more - but its the images I am looking for) from both camera and file system..
In the web version http://carbonyzed.co.uk/websites/assent/1/photos.html this works great from my phone, but when converted to .apk, this functionality is lost, and I can't seem to find anything on here, or online relating to this issue.
At least for me, the input file doesn't work in Phonegap.
You need use the Phonegap API to get picture and select the source where come from, like photolibrary, camera or savedphotoalbum.
See more info about camera.getPicture: http://docs.phonegap.com/en/2.1.0/cordova_camera_camera.md.html#camera.getPicture
and about Camera.PictureSourceType parameter of cameraOptions method: http://docs.phonegap.com/en/2.1.0/cordova_camera_camera.md.html#cameraOptions
Ended up using the Child Browser system like so
In the head
<script src="childbrowser.js"></script>
in the body
<button class="button-big" onClick="window.plugins.childBrowser.showWebPage('URL_TO_GO_HERE',
{ showAddress: false });" style="width: 100%;">UPLOAD PHOTOS</button>
which has a standard fileuploader like
<input name="file" type="file" id="file">
then it let me select from root storage, works in phonegap 2.2 onwards on both iOS and Android OS
To capture an image I used this in the head
<script type="text/javascript" charset="utf-8" src="json2.js"></script>
<script type="text/javascript" charset="utf-8">
// Called when capture operation is finished
//
function captureSuccess(mediaFiles) {
var i, len;
for (i = 0, len = mediaFiles.length; i < len; i += 1) {
uploadFile(mediaFiles[i]);
}
}
// Called if something bad happens.
//
function captureError(error) {
var msg = 'An error occurred during capture: ' + error.code;
navigator.notification.alert(msg, null, 'Uh oh!');
}
// A button will call this function
//
function captureImage() {
// Launch device camera application,
// allowing user to capture up to 2 images
navigator.device.capture.captureImage(captureSuccess, captureError, {limit: 2});
}
// Upload files to server
function uploadFile(mediaFile) {
var ft = new FileTransfer(),
path = mediaFile.fullPath,
name = mediaFile.name;
ft.upload(path,
"http://my.domain.com/upload.php",
function(result) {
console.log('Upload success: ' + result.responseCode);
console.log(result.bytesSent + ' bytes sent');
},
function(error) {
console.log('Error uploading file ' + path + ': ' + error.code);
},
{ fileName: name });
}
</script>
and this in the body
<input type="button" class="button-big" style="width: 100%;" onclick="captureImage();" value="TAKE PHOTO">
copy and past and it works a dream,
Check it out in this image
any questions, just email comment,
or email me... support#carbonyzed.co.uk

Different encoding issue

I'm writing an android app that implements a web server that sends pages containing text messages.
By client side I developed a web interface. This interface contains some DIVs that are filled using ajax and in particular with this functions that gets a page and put it into a specified div:
function getElementFromId(myElement) {
var elem;
if(document.getElementById)
elem = document.getElementById(myElement);
else
elem = document.all[myElement];
return elem;
}
function getXMLHttpRequest() {
var XHR = null, browser = navigator.userAgent.toUpperCase();
if(typeof(XMLHttpRequest) == "function" || typeof(XMLHttpRequest) == "object")
XHR = new XMLHttpRequest();
else if(window.ActiveXObject && browser.indexOf("MSIE 4") < 0) {
if(browser.indexOf("MSIE 5") < 0)
XHR = new ActiveXObject("Msxml2.XMLHTTP");
else
XHR = new ActiveXObject("Microsoft.XMLHTTP");
}
return XHR;
}
function pageInDiv(nomeFile,divId) {
var ajax = getXMLHttpRequest(), elem = getElementFromId(divId),
usaLink = true;
if(ajax) {
usaLink = false;
ajax.open("get", nomeFile, true);
//ajax.setRequestHeader("connection", "close");
ajax.onreadystatechange = function() {
if(ajax.readyState == 4) {
if(ajax.status == 200)
elem.innerHTML = ajax.responseText;
else
elem.innerHTML += "Error: " + statusText[ajax.status];
}
}
ajax.send(null);
}
return usaLink;
}
Now there's the problem! When I call pageInDiv("pageWithText.html",myDiv) the div is filled correctly, except for accented caracters. If the text contains àèìòù, the div will contain strange symbols, but (this is the strangest thing) if I open the page http://.../pageWithText.html directly in the browser it appears perfectly!
What's the problem? Thank you in advice
Update
This a piece of the web interface code:
<body onLoad=" pageInDiv('conversations.html', 'conversations');>
And this is the code of conversations.html:
<div id="conversations" class="list">
<div id="main">
<div id="msgTitle">Io</div>
<div id="message"><div id="img">
<img class="convimg" src="contactphoto_8259.jpg"></div>
<div id="text">������</div></div><div id="line"></div>
</div>
You should try to include the following code in the html page where you have these encoding problems
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html>
<head>
<meta http-equiv="content-type" content="application/xhtml+xml; charset=UTF-8" />
...
</head>
If this encoding it's not working (I doubt it) you can try with different code from this page.

Categories

Resources