Friday, January 24, 2014

JqueryMobile very useful technique

Changing the text of a button at runtime
If you are trying to update the value of a button at run time then create the button with
<input type = "button" id="total_time" value= "Time : 00.00" class="ui-btn-right">
but not with <a href="" data-role="button">
You get the below error
 can not call method of button before initialization error.

Set the for attribute of the label to match the ID of the input so they are semantically associated and wrap them in a div with the data-role="fieldcontain" attribute to group them.

<div data-role="fieldcontain">
    <label for="password">Password Input:</label>
    <input type="password" name="password" id="password" value="" />
</div>

Grouping and dividing content

jQuery Mobile provides classes ui-bar and ui-body for subdividing and for visually grouping content.

Add class ui-bar to create a full-width heading or a separator between sections of content.
Additionally, classes ui-bar-[a-z] add the appropriate swatch from your theme.

Add class ui-body to visual group and/or emphasize a section of content.
Additionally, classes ui-body-[a-z] add the appropriate swatch from your theme.

<div id="are_you_lost" data-inline="true" align="center">
<h3 class="ui-bar ui-bar-b ui-corner-all" id="high_scrore_header">Are You Lost ?</h3>
 <div class="ui-body ui-body-b ui-corner-all">
<p>There is a keyboard for you at upper right corner !
  </br>Click it and start playing.</br></p>
  </div>
</div>

Creating a DialogBox like Popup

<div id="success_dialog" data-position-to="window" data-role="popup" data-history="false" data-transition="flip">
 <h3 class="ui-bar">Header </h3>
   <div class="ui-body ui-body-b">
  <p>This is a content
    </br>This is a content</br>
    </br>This is a content</br>
      </br></p>
                            </div>

</div>

This is a better example
<a href="#popupDialog" data-rel="popup" data-position-to="window" data-role="button" data-inline="true" data-transition="pop" data-icon="delete" data-theme="b">Delete page...</a>
<div data-role="popup" id="popupDialog" data-overlay-theme="a" data-theme="c" data-dismissible="false" style="max-width:400px;" class="ui-corner-all">
    <div data-role="header" data-theme="a" class="ui-corner-top">
        <h1>Delete Page?</h1>
    </div>
    <div data-role="content" data-theme="d" class="ui-corner-bottom ui-content">
        <h3 class="ui-title">Are you sure you want to delete this page?</h3>
        <p>This action cannot be undone.</p>
        <a href="#" data-role="button" data-inline="true" data-rel="back" data-theme="c">Cancel</a>
        <a href="#" data-role="button" data-inline="true" data-rel="back" data-transition="flow" data-theme="b">Delete</a>
    </div>
</div>

Creating grouped button

You can group buttons together and put them together in fotter/header e.g

<div data-role="controlgroup" data-type="horizontal" class="ui-btn-left">
<a href="quit.html" data-icon="delete" data-ajax="false" data-role="button">Quit</a>
<input type = "button" id="total_tries" value= "Tries : 0" >
</div>

Prevent ChangePage
-----------------
$(document).bind('pagebeforechange', function(e, data) {
    var to = data.toPage,
        from = data.options.fromPage;

    if (typeof to === 'string') {
        var u = $.mobile.path.parseUrl(to);
        to = u.hash || '#' + u.pathname.substring(1);
        if (from) from = '#' + from.attr('id');

        if (from === '#page1' && to === '#page3') {
            alert('Cannot change to page 3 from page 1');
            e.preventDefault();

            // remove active class on button
            // otherwise button would remain highlighted
            $.mobile.activePage
                .find('.ui-btn-active')
                .removeClass('ui-btn-active');
        }          
    }
});


How to display a scrollbar in a div  This is best way to display more informations in a Game

$(document).on("pageinit","#pageone",function(event){

var heightOfWindow = $(window).height();
var totalHeightOfContents = $(document).height();
if(heightOfWindow <= totalHeightOfContents){
var contentIDHeight = $('#content_id').height();
var infoDivIDHeight = $('#info').height();
var heightExcludingInfo = contentIDHeight - infoDivIDHeight;
var availableHeightForInfo = heightOfWindow - heightExcludingInfo;
var test = availableHeightForInfo - 420;
$('#info').height(test);
}
});

Tuesday, January 21, 2014

JqueryMobile Headers Footer Navigation Bars

Create own custom Header/Fotter Bars

<div data-role="footer" class="ui-bar">
<a href="index.html" data-role="button" data-icon="plus">Add</a>
<a href="index.html" data-role="button" data-icon="arrow-u">Up</a>
<a href="index.html" data-role="button" data-icon="arrow-d" class="ui-btn-right">Down</a>
</div>

Note that .ui-bar should not be added to header or footer bars that span the full width of the page


To Create FullScreen Headers which goes away in fullscreen mode
<div data-role="header" data-fullscreen="true">

Alignment and grouping
To align all elements center in the header/footer use alighn="center" style
<div data-role="header" align="center" data-position="fixed">

use data-role="controlgroup" for grouping the buttons in headers or footers

<div data-role="footer" id="id_footer" data-position="fixed">
<div data-role="controlgroup" data-type="horizontal">
<input type = "button" id="total_tries" value= "Tries : 0">
<input type = "button" id="total_giveup" value= "GiveUp">
</div>
<input type = "button" id="total_time" class="ui-btn-right">
</div>

Navbar
A navbar is coded as an unordered list of links wrapped in a container element that has the data-role="navbar" attribute. This is an example of a two-button navbar:

<div data-role="navbar">
 <ul>
  <li><a href="a.html">One</a></li>
  <li><a href="b.html">Two</a></li>
 </ul>
</div><!-- /navbar -->

Navbar in Headers
If you want to add a navbar to the top of the page, you can still have a page title and buttons. Just add the navbar container inside the header block, right after the title and buttons in the source order.

Persistent navbar
There is also a persistent navbar variation that works more like a tab bar that stays fixed as you navigate across pages. To tell the framework to apply the persistent behavior, add the same data-id attribute to the header and/or footer of all HTML pages in the navigation

<div data-role="footer" data-id="foo1" data-position="fixed">
 <div data-role="navbar">
  <ul>
   <li><a href="a.html">Info</a></li>
   <li><a href="b.html">Friends</a></li>
   <li><a href="c.html">Albums</a></li>
   <li><a href="d.html">Emails</a></li>
  </ul>
 </div><!-- /navbar -->
</div><!-- /footer -->

To set the active state of an item in a persistent toolbar, add class="ui-btn-active ui-state-persist" to the corresponding anchor.
 
<li><a href="a.html" class="ui-btn-active ui-state-persist">Info</a></li>


Saturday, January 18, 2014

Creating an Application using PhoneGap (Cordova) with target android

Install Node js will install npm and other necessary component for phonegap utility
Install PhoneGap : npm install -g phonegap
Install Cordova : npm install -g phonegap

Go to Your Workspace Directory and Create a cordova project

cordova create CowsBulls com.zoogaru.games CowsBulls -d

-d option displays information about its progress.

It Creates following forlders

.cordova
merges
platforms --- all added platform code goes here..
plugins --- all installed plugins sits here
www --- root directory for the application assets like css, img, html, js present

WWW Folder
subdirectory houses your application's home page, along with various resources under cssjs, and img, which follow common web development file-naming conventions

Setting up for Android
Pre-requiste -- Android platform is available and emulator device setup is done

Set up environment variables
Create A UserVariable ANDROID_TOOLS = D:\Android\sdk\platform-tools;D:\Android\sdk\tools
Add it to Path variable = PATH;ANDROID_TOOLS

Install Java SDK and set path unless java runs from  command line

Install ant from below link zip version or which ever is applicable for your os
http://ant.apache.org/bindownload.cgi
Follow instructions at http://ant.apache.org/manual/install.html to setup ant

The ant.bat script makes use of three environment variables - ANT_HOME, CLASSPATH and JAVA_HOME. Ensure that ANT_HOME and JAVA_HOME variables are set, and that they do not have quotes (either ' or ") and they do not end with \ or with /. CLASSPATH should be unset or empty.

Create ANT_HOME
Create JAVA_HOME

set ANT_HOME=c:\ant
set JAVA_HOME=c:\jdk1.7.0_51
set PATH=%PATH%;%ANT_HOME%\bin

Now Check the ANT SetUp

You can check the basic installation with opening a new shell and typing ant. You should get a message like this
Buildfile: build.xml does not exist!
Build failed
So Ant works. This message is there because you need to write an individual buildfile for your project. With a ant -version you should get an output like

add android platform
D:\workspace\HTML5\CowsBulls>cordova platform add android
Creating android project...
Preparing android project

build
D:\workspace\HTML5\CowsBulls>cordova build
Generating config.xml from defaults for platform "android"
Preparing android project
Compiling app on platform "android" via command "cmd" /c D:\workspace\HTML5\Cows
Bulls\platforms\android\cordova\build
Platform "android" compiled successfully.

run in device
D:\workspace\HTML5\CowsBulls>cordova run
Generating config.xml from defaults for platform "android"
Preparing android project
Running app on platform "android" via command "cmd" /c D:\workspace\HTML5\CowsBu
lls\platforms\android\cordova\run --device
Platform "android" ran successfully.

Our Application might use internet so enable internet plugin
install git command line tool from http://git-scm.com/
Access files on device or network (File API):

D:\workspace\HTML5\CowsBulls>phonegap local plugin add https://git-wip-us.apache
.org/repos/asf/cordova-plugin-file.git
[phonegap] adding the plugin: https://git-wip-us.apache.org/repos/asf/cordova-pl
ugin-file.git
[phonegap] successfully added the plugin

D:\workspace\HTML5\CowsBulls>phonegap local plugin add https://git-wip-us.apache
.org/repos/asf/cordova-plugin-vibration.git
[phonegap] adding the plugin: https://git-wip-us.apache.org/repos/asf/cordova-pl
ugin-vibration.git

[phonegap] successfully added the plugin


Add DialogBox and Vibration tool for notifications
D:\workspace\HTML5\CowsBulls>phonegap local plugin add https://git-wip-us.apache
.org/repos/asf/cordova-plugin-dialogs.git
[phonegap] adding the plugin: https://git-wip-us.apache.org/repos/asf/cordova-pl
ugin-dialogs.git

[phonegap] successfully added the plugin

Open new browser windows (InAppBrowser):

$ phonegap local plugin add https://git-wip-us.apache.org/repos/asf/cordova-plugin-inappbrowser.git

Debug console:


$ phonegap local plugin add https://git-wip-us.apache.org/repos/asf/cordova-plugin-console.git

To List all Plugins

D:\workspace\HTML5\CowsBulls> phonegap local plugin list
[phonegap] org.apache.cordova.console
[phonegap] org.apache.cordova.dialogs
[phonegap] org.apache.cordova.file
[phonegap] org.apache.cordova.inappbrowser

[phonegap] org.apache.cordova.vibration

The config.xml File
Many aspects of an app's behavior can be controlled with a global configuration file, config.xml
config.xml file can be found in the top-level www directory
 D:\workspace\HTML5\CowsBulls\www

Read ..
http://docs.phonegap.com/en/edge/config_ref_index.md.html#The%20config.xml%20File

Setting Global Level preferences
Full Screen true/false and Orientation portrait/landscape
<preference name="Fullscreen" value="true" />
<preference name="Orientation" value="landscape" />

The came config gets copied to the folder
D:\workspace\HTML5\CowsBulls\platforms\android\assets\www

There is also one config file which android specific
D:\workspace\HTML5\CowsBulls\platforms\android\res\xml\
where you see device specific plugin informations are added e.g
    <feature name="Notification">
        <param name="android-package" value="org.apache.cordova.dialogs.Notification" />
    </feature>

NOW LETS ENABLE OUR HTML5 GAME in Cordova

drop all the html file to application/www folder
run the cordova build command
Check all the files got copeid to
D:\workspace\HTML5\CowsBulls\platforms\android\assets\www

Change the <content src="index.html" /> to
<content src="home.html" /> to point to your application landing page

And you are done !!

Now Create a Icon for the android
create a image icon using GIMP or photoshop
use the android asset tool and generate icon from the image.
use http://makeappicon.com/ for creating icon for android/ihone device

Splash Screen
http://android-ui-utils.googlecode.com/hg/asset-studio/dist/nine-patches.html

Create the release version
cordova build --release

Signing process
keytool -genkey -v -keystore my-release-key.keystore-alias alias_name -keyalg RSA -keysize 2048 -validity 10000
jarsigner -verbose -sigalg SHA1withRSA -digestalg SHA1 -keystore my-release-key.keystore my_application.apk alias_name
jarsigner -verify my_signed.apk
zipalign -v 4 your_project_name-unaligned.apk your_project_name.apk

HTML5 Page Linking, Navigation, Pagechange, Load

Linking external pages or different page resource in the same domain

Links that point to other domains or that have rel="external", data-ajax="false" or target attributes will not be loaded with AJAX. Instead, these links will cause a full page refresh with no animated transition. Both attributes (rel="external" and data-ajax="false") have the same effect, but a different semantic meaning: rel="external" should be used when linking to another site or domain, while data-ajax="false" is useful for simply opting a page within your domain from being loaded via AJAX. Because of security restrictions, the framework always opts links to external domains out of the AJAX behavior.

It's important to note that if you are linking from a mobile page that was loaded via AJAX to a page that contains multiple internal pages, you need to add a rel="external" or data-ajax="false" to the link. This tells the framework to do a full page reload to clear out the AJAX hash in the URL. This is critical because AJAX pages use the hash (#) to track the AJAX history, while multiple internal pages use the hash to indicate internal pages so there will be conflicts in the hash between these two modes.

For example, a link to a page containing multiple internal pages would look like this:
<a href="multipage.html" rel="external">Multi-page link</a>

When linking to directories, without a filename URL, (such as href="typesofcats/" instead ofhref="typesofcats/index.html"), you must provide a trailing slash. This is because jQuery Mobile assumes the section after the last "/" character in a URL is a filename, and it will remove that section when creating base URLs from which future pages will be referenced.
Documents loaded via AJAX will select the first page in the DOM of that document to be loaded as a jQuery Mobile page element. As a result the developer must make sure to manage the id attributes of the loaded page and child elements to prevent confusion when manipulating the DOM.
If you link to a multipage document, you must use a data-ajax="false" attribute on the link to cause a full page refresh due to the limitation above where we only load the first page node in an AJAX request due to potential hash collisions

While linking pages inside a multipage template, you should not use the data-ajax="false" attribute as it is of no use and will only interfere with the transition settings.
The "ui-page" key name used in sub-hash URL references can be set to any value you'd like, so as to blend into your URL structure. This value is stored in jQuery.mobile.subPageUrlKey.
jQuery Mobile Load Events
Page load events are for external pages.
Whenever an external page is loaded into the DOM, 2 events fire. The first is pagebeforeload, and the second will either be pageload (success) or pageloadfailed (fail).
These events are explained in the table below:

back Button Linking
<a data-rel="back" data-icon="arrow-l">Back</a>

You can disable button style of active buttons after stop transition
$.mobile.activeBtnClass = 'unused';

Serialize the form data with jQuery
var serializedFormData = $('#form').serialize();
Third: Post your form with $.ajax();
$.ajax({
   url: '/countries/change_country',
   type: 'POST',
   data: serializedFormData
});

Using Web Storage

What is HTML5 Web Storage?

With HTML5, web pages can store data locally within the user's browser.
Earlier, this was done with cookies. However, Web Storage is more secure and faster. The data is not included with every server request, but used ONLY when asked for. It is also possible to store large amounts of data, without affecting the website's performance.

The data is stored in key/value pairs, and a web page can only access data stored by itself.

localStorage and sessionStorage 
There are two new objects for storing data on the client:
  • localStorage - stores data with no expiration date

The localStorage object stores the data with no expiration date. The data will not be deleted when the browser is closed, and will be available the next day, week, or year.
  • sessionStorage - stores data for one session
  • it persists in the same tab, being the origin of the context, and in every page surfed inside the tab, so it could be extremely unsafe to trust it for important data
  • it is automatically cleaned as soon as we close the tab or the browser, so used RAM will be automatically cleaned and without scripting effort
Before using web storage, check browser support for localStorage and sessionStorage:
if(typeof(Storage)!=="undefined")
  {
  // localStorage and sessionStorage code goes here
  }
else
  {
  // Your Webbrowser doesn't support webstorage !
  }

We are going to use Session storage to save username and password. 

        function getServerPwd(aName) {
            if (typeof (Storage) !== "undefined") {
                if (!sessionStorage.user_name) {
                    sessionStorage.user_name = aName;
                    sessionStorage.user_pwd = getHashPwd(aName);
                }
                return sessionStorage.user_pwd;
            }
            else {
                alert("browser doesn't support session data !");
            }
            return "";
        }

        function getHashPwd(aName)
        {

        var hash = 0, i, char;
   if (aName.length == 0) return hash;
   for (i = 0, l = aName.length; i < l; i++) {
       char  = aName.charCodeAt(i);
       hash  = ((hash<<5)-hash)+char;
       hash |= 0; // Convert to 32bit integer
   }
    return hash;
        }