jQuery Mobile Cookbook

By Chetan K Jain
  • Instant online access to over 7,500+ books and videos
  • Constantly updated with 100+ new titles each month
  • Breadth and depth in over 1,000+ technologies
  1. Get Rolling

About this book

jQuery Mobile is an award winning, HTML5/CSS3 based open source cross-platform UI framework. It offers a very cool and highly customizable UX. It is built on the popular jQuery library and uses declarative coding making it  easy to use and learn. It is the market leader today considering the numerous browsers and platforms that it supports.

"jQuery Mobile Cookbook" presents over a hundred recipes written in a simple and easy manner. You can quickly learn and start writing code immediately. Advanced topics such as using scripts to manipulate, customize, and extend the framework are also covered. These tips address your common everyday problems. The book is very handy for both beginner and experienced jQuery Mobile developers.

You start by developing simple apps using various controls and learn to customize them. Later you explore using advanced aspects like configurations, events, and methods.
Develop single and multi-page applications. Use caching to boost performance. Use custom transitions, icon sprites, styles, and themes. Learn advanced features like configurations, events, and methods. Explore future trends by using HTML5 new features and semantics with jQuery Mobile.

"jQuery Mobile Cookbook" is an easy read and is packed with practical tips and screenshots.

Publication date:
November 2012
Publisher
Packt
Pages
320
ISBN
9781849517225

 

Chapter 1. Get Rolling

In this chapter, we will cover the following recipes:

  • Writing your first jQuery Mobile application

  • Using JS Bin to create a simple application

 

Introduction


The jQuery Mobile Framework is an open source cross-platform UI framework. It is built using HTML5, CSS3, and the very popular jQuery JavaScript library, and it follows Open Web standards. It provides touch-friendly UI widgets that are specially styled for mobile devices. It has a powerful theming framework to style your applications. It supports AJAX for various tasks, such as page navigation and transitions.

As jQuery Mobile follows the open web standards, you can be sure that your application can get maximum support and compatibility with a wide range of browsers and platforms. You can write your application once and it will work seamlessly on iPhones, iPads, Android phones and tablets, Blackberry, Bada, Windows, Symbian, Meego, and even the upcoming HTML5-based platforms, such as Boot2Gecko and Tizen. The same code will run on Chrome, Firefox, Opera, IE, Safari, and other browsers on your desktop. Further, it will work even on your smart TV or any other gadget that has a compatible browser which is compliant with the open web standards. The market reach potential is phenomenal.

The list of the currently certified supported browsers, platforms, and the grade of support is available on the jQuery Mobile website at http://www.jquerymobile.com/gbs. Note that some features, such as CSS 3D animations and AJAX, might not be supported on certain older and legacy platforms. Here, the framework resorts to Progressive Enhancement. This means that the basic functionality is supported initially. Later, when a more capable future browser or platform becomes available, your application automatically makes use of its capabilities and offers upgraded functionality. In most scenarios, you will not have to write the code or interfere in any way. This is a big plus when you compare mobile web applications with mobile native applications.

While coding native applications, you will have to write the code in different languages, based on the platform. You will then have to compile the code for each platform, and build binary packages that can run on the device. Upgrading the application to support the next version means you have to go back and redo the whole exercise of checking/fixing your code, rebuilding, and repackaging. This overhead compounds as you add support for more platforms. The whole thing just becomes unmanageable after a point. You are better off by just supporting the top one or two platforms for your application.

Of course, there are advantages of using native applications. The performance of your application could be a very crucial factor. There are certain applications where you have to go native, especially when you expect real-time responses. Also, with native apps, you can access core OS and device features, such as camera, accelerometer, contacts, and calendar. This is not easily done today with HTML5.

HTML5 is a relatively new entrant for mobile applications. But the gap is closing by the day. There are libraries already available that expose the native features using simple JavaScript API, which is directly available to your HTML5 app. PhoneGap is one such popular library. Firefox's Boot2Gecko and Intel/Samsung's Tizen are totally based on HTML5, and you should be able to access the core device functionality directly from the browser here. Things do look very promising for the future.

The jQuery Mobile framework has a wide array of plugins and tools that help you build your application. It has a very active and vibrant developer community, and new features are continuously being added. It is strongly backed by companies, such as Filament Group, Mozilla, Nokia, Palm, Adobe, Rhomobile, and others. Within its first year (in 2011), the framework has already won awards, such as the Packt Open Source Award and the .NET Innovation Award.

Web-based mobile applications have evolved. They used pure native code for the UI in the early days, then came flash and other plugin-based UI (such as Silverlight). But even Adobe and Microsoft (with its Windows 8 platform) are going full steam ahead on HTML5 development. So, the situation is ripe for the explosive growth of an open source web standards-based cross-platform framework, such as jQuery Mobile.

The jQuery Mobile framework requires you to use declarative syntax (HTML markup) for most of the basic tasks and for building the UI. You have to fall back to scripting with JavaScript only, where declarative syntax does not help, and of course for adding your application logic. This is different from many other UI frameworks that are available in the market today. The other frameworks require you to write much more JavaScript and have a much steeper learning curve.

If you are familiar with HTML, CSS, and jQuery/JavaScript, then you will find it very easy to learn jQuery Mobile. There are many popular IDEs and UI builders that you can use to visually drag-and-drop UI controls and develop in jQuery Mobile. But to get started, all you need is your favorite text editor to write the code. You will also need a browser (running on your desktop or mobile) to test the application. You are now ready to write your first jQuery Mobile cross-platform application.

 

Writing your first jQuery Mobile application


A simple jQuery Mobile application consists of a page, which forms the basic building block for your application. The page follows a basic structure with three main parts, the header , the page content , and the footer . You can build feature-rich applications with workflows using multiple pages, each page with its own functionality, logic, and navigational flow. This recipe shows how to create a page and write your first jQuery Mobile application.

Getting ready

Copy the full code of this recipe from the code/01/welcome folder. You can launch this code using the URL: http://localhost:8080/01/welcome/main.html.

How to do it...

Carry out the following steps:

  1. Create the following main.html file using your favorite text editor:

    <!DOCTYPE html>
    <html>
      <head>
        <title>Welcome</title>
        <meta name='viewport' content='width=device-width, 
          initial-scale=1'>
  2. Include the jQuery and jQuery Mobile JavaScript files:

        <link rel='stylesheet' href='http://code.jquery.com
          /mobile/1.1.1/jquery.mobile-1.1.1.min.css' />
        <script src='http://code.jquery.com/jquery-
          1.7.1.min.js'></script>
        <script src='http://code.jquery.com/mobile
          /1.1.1/jquery.mobile-1.1.1.min.js'></script>
      </head>
      <body>
  3. Create the jQuery Mobile page:

        <!-- Main Page -->
        <div id='main' data-role='page'>
          <div data-role='header'>
            <h1>Welcome!</h1>
          </div>
          <div id='content' data-role='content'>
            <p>The jQuery Mobile Cookbook</p>
          </div>
          <div data-role='footer'>
            <h4>Enjoy reading the book ...</h4>
          </div>
        </div>
      </body>
    </html>

How it works...

Create main.html as an HTML5 document starting with the <!DOCTYPE html> declaration. In the <head> tag of the file, add a <meta> tag and specify that the viewport should occupy the entire device width by using the content='width=device-width' attribute. Include the jQuery Mobile stylesheet by using the <link> tag pointing to the CSS file location on the jQuery Mobile Content Delivery Network (CDN) site.

Next, include the JavaScript libraries; first the jQuery and then the jQuery Mobile JavaScript files. Use the <script> tags and point src to the CDN location, as shown in the code. You are now ready to create the page.

The page, its header, footer, and content are all <div> containers, which are styled by using the data-role attributes. Add a <div> tag with data-role='page' to the <body> tag. Add three div tags with data-role='header', 'content', and finally the 'footer' as child elements within the page. This will create the page header, content, and footer respectively. You can add any text, forms, lists, or other HTML controls within these <div> tags. The framework will enhance and render the controls in a touch-friendly mobile-enabled style.

Now, open the main.html file in your favorite browser, and you will see an output similar to the following screenshot:

Open and compare the output of this file in different browsers, mobile devices, and tablets. You will see that on all-compliant and certified browsers/devices, the page opens up and looks pretty much the same.

Congratulations! You just created your first cross-platform jQuery Mobile web application.

There's more...

At the time of writing this recipe, jQuery Mobile v1.1.1 was the stable version and is used in all the recipes in this book. The supported jQuery library recommended is jQuery v1.7.1.

You can use the libraries directly from the jQuery Mobile CDN, as shown in this recipe. You could also download the library files (available in a single archive) at http://www.jquerymobile.com/download, and host the files locally within your network. When hosted locally, you just have to update the links in your code to point to the correct location of the files on your network (or to the path on your hard disk), as shown in the following code snippet:

<link rel="stylesheet" href='[local path]/jquery.mobile-
  1.1.1.min.css' />
<script src='[local path]/jquery-1.7.1.min.js'></script>
<script src='[local path]/mobile/1.1.1/jquery.mobile-
  1.1.1.min.js'></script>

The Page theme

By default, the framework provides five basic color schemes or combinations called color swatches . They are named a, b, c, d and e. By default, swatch d is used when you create a page. This gives the page a bright combination of white and black colors, as seen in the previous screenshot. You can change the color swatch of your page and header/footer by using the data-theme attribute, as shown in the following code snippet:

<div data-role='page' data-theme='a'>
  <div data-role='header' data-theme='b'>
….
  <div data-role='footer' data-theme='b'>

The output will now be similar to the following screenshot:

See also

  • The Using JS Bin to create a simple application recipe

  • The Writing a single-page template application and Writing a multi-page template application recipes in Chapter 2, Pages and Dialogs

 

Using JS Bin to create a simple application


JS Bin is an open source web application built by Remy Sharp, available at http://www.jsbin.com. JS Bin allows you to directly enter your HTML, CSS, and JavaScript code online, and also allows you to include the required jQuery and jQuery Mobile libraries. You can add and directly run your JavaScript code and preview the output on your browser. You can also share your code and collaborate with others for review or troubleshooting. You can finally download your code once everything works as desired. It is a very popular tool used by many jQuery Mobile developers. This recipe shows you how to create a simple jQuery Mobile application using JS Bin.

Getting ready

The code in this recipe was created using the JS Bin web application available at http://www.jsbin.com. The code is available in the code/01/jsbin source folder. You can launch the code using the URL http://localhost:8080/01/jsbin/main.html.

How to do it...

  1. Launch the JS Bin web application tool at the URL http://www.jsbin.com, and you will see a basic HTML template.

  2. Select the Add Library link on the top-left panel, and include the latest jQuery Mobile library files. Next, edit the <head> section, as shown in the following code snippet:

    <html>
      <head>
        <link href="http://code.jquery.com/mobile/latest
          /jquery.mobile.css" rel="stylesheet" type="text/css" />
        <script src="http://code.jquery.com
          /jquery-1.7.1.min.js"></script>
        <script src="http://code.jquery.com
          /mobile/latest/jquery.mobile.js"></script>
        <meta name="viewport" content="width=device-width, 
          initial-scale=1">
        <title>Welcome using JS Bin</title>
      </head>
  3. Add code to the <body> section to create a simple jQuery Mobile page:

      <body>
        <!-- Main Page -->
        <div id="main" data-role="page">
          <div data-role="header">
            <h1>Welcome - JS BIN</h1>
          </div>
          <div id="content" data-role="content">
            <p>The jQuery Mobile Cookbook</p>
          </div>
          <div data-role="footer">
            <h4>Enjoy reading the book ...</h4>
          </div>
        </div>
      </body>
    </html>
  4. The preview or output is now visible in the Output pane on the right side of the screen.

  5. You can now download the source file (or copy-and-paste into a local file) to have a simple working jQuery Mobile application.

How it works...

Launch the JS Bin web application in your browser. You will see the following screen in your browser, with a basic HTML template (which you can edit) on the left side. A menu bar is available at the top and an Output pane is available on the right, to instantly preview the output of your code:

You can click on the various menu options and see how the CSS or JavaScript panes can be made visible or hidden. Selecting the Auto-run JS option will allow you to run your JS code automatically; you can leave it on. You can also manually run the script by clicking on the Run with JS button.

Click on the Add library menu option and select the jQuery Mobile Latest option as shown in the following screenshot:

This will include the links and references to the jQuery Mobile and jQuery libraries in the <head> section of the HTML.

Note

When you add the jQuery Mobile library to your code using JS Bin, make sure you edit and set the correct versions for both jQuery Mobile and jQuery libraries that you want to use with your application. When this recipe was written, jQuery v1.6.4 was being used in JS Bin, whereas jQuery v1.7.1 is recommended to be used with jQuery Mobile v1.1.1.

Next, edit the <meta> tag to set the correct viewport width and scale, as shown in the code. Then, add a page to the <body> tag using a div tag with data-role="page". Create the header (data-role="header"), page content (data-role="content"), and footer (data-role="footer"), as shown. As you add these sections, you will notice that the Output pane on the right side of the screen gets updated and shows the output preview of your code.

You can also add CSS styles and JavaScript, and check how it works. Finally, your code is ready and you can copy-and-paste it locally into your editor. You can also click on the JS Bin menu option at the top-left to download the file. Now, launch the local file in your browser, and you will see that the output matches what was displayed in the Output pane of JS Bin.

There's more...

This recipe shows you the simple steps required to create a basic jQuery Mobile application using JS Bin. JS Bin provides many features that are nice to use, such as creating and using ready templates, saving and forking your code using GitHub, and cloning your code. This tool is best suited for when you want to store your files online and collaborate on your source files. For more information and tutorials on using JS Bin, refer to http://jsbin.tumblr.com/.

Note

You can register for free and log in to JS Bin with your user account to make use of the save, download, or clone features. Only the basic features are available without user login.

See also

  • The Writing your first jQuery Mobile application recipe

About the Author

  • Chetan K Jain

    Chetan K Jain loves to code, and has been writing code for over 16 years now. He is a Senior Architect, and has worked on mobile technologies for over 4 years for Nokia. Since then, he has moved on to work as a freelance consultant. Chetan has significant experience in writing cross-platform mobile apps using jQuery Mobile, HTML5, CSS3, JavaScript, Nodejs, and has also worked extensively on Qt. Prior to mobile technologies, he has worked with Java technology and was also certified as an MCSD and MCSE in his early days. Chetan is an active contributor to open source development, and tries to help jQuery Mobile development whenever he can. He regularly participates in developer forums, and was earlier a top-ranked member and a "mad scientist" in the Nokia Qt Developer Forum. Chetan was born in Bangalore and lives there with his wife Shwetha and son Tanmay. The only time he ventured to live away from Bangalore was when he worked for over 4 years in the USA. His adventure didn't end there. He did a solo US cross country drive in his two door coupe from the east coast to the west and back, driving alone for over 8000 plus miles in 16 days to experience and live life as he calls it. His travelogue can be found at http://adventure.chetankjain.net. Chetan has contributed and published over 15 books to Gutenberg as a volunteer. He has also published four books on Jaina Literature and History written by his mother Saraswathamma. He is a voracious reader, and his other interests include music, movies, and travelling. Photography is his favorite hobby, and his clicks can be found at http://www.facebook.com/chetankjainphotos/photos_stream. Chetan can be reached at [email protected] He also blogs at http://dev.chetankjain.net.

    Browse publications by this author
Book Title
Access this book, plus 7,500 other titles for FREE
Access now