jQuery Mobile framework – Beginner Tutorial

Being able to reach your audience via a mobile page is becoming almost as important as having a page at all but getting started in mobile site development can be frustrating. The jQuery library provides many handy mobile features that you can use to get started making great mobile-friendly web sites. In this article I will discuss the jQuery mobile framework features and give you a little demo on how it works.

What is jQuery Mobile?

jQuery Mobile is a unified framework that is designed to work on all major mobile platforms. This allows us to save a lot of time in development since we no longer have to think about different platform problems or write separate pages for different devices. The framework was designed around the touch-screen concept and has many built-in tools to help you design touch-friendly interfaces. You can create themes for your site that are designed around various form-factors of the screen so your page will look just as great on a phone as it does on a tablet. This is an excellent breakthrough for developers that need to work in the mobile phone or tablet setting and ultimately saves a lot of time and frustration.

How to Get Started

Getting started writing jQuery Mobile applications is not really that different from writing jQuery for a traditional site. You can get a basic page template from the jQuery Mobile Quick Start Guide that can serve as a starting template for your page. Here is an example of the template page:

<!DOCTYPE html>
<html>
    <head>
    <title>My Page</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="http://code.jquery.com/mobile/1.0/jquery.mobile-1.0.min.css" />
    <script type="text/javascript" src="http://code.jquery.com/jquery-1.6.4.min.js"></script>
    <script type="text/javascript" src="http://code.jquery.com/mobile/1.0/jquery.mobile-1.0.min.js"></script>
</head>
<body>
<div data-role="page">
    <div data-role="header">
        <h1>My Title</h1>
    </div><!-- /header -->
    <div data-role="content">
        <p>Hello world</p>     
    </div><!-- /content -->
</div><!-- /page -->
</body>
</html>

This template already contains the elements needed to serve your page for the particular screen width. There are several wrappers set up in the template that delineate between header and content sections. Although these wrappers are optional, they are nice to have and make creating the different areas of your page easier. These new data- attributes are part of HTML5 and transform the markup in the wrapper to a styled widget when rendered.

Once you have this basic template downloaded, you can begin editing to add the usual HTML elements you may need inside the content container. If you want to add custom layouts or addition styles you can add another stylesheet to the head section after the jQuery Mobile stylesheet. There are also many new jQuery Mobile controls that you can add to your page that will render nicely in your mobile environment. These controls include items such as buttons, sliders, lists, text areas, menus and switches. Here are some examples:

To create a text input field:

<input type="text" name="name" id="basic" value=""  />

This creates a basic text box that is 100% of the parent container. You can specify a particular width if needed as well as use the data-role attribute to group the text box with other form elements, like so:

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

When linking between pages using jQuery Mobile, you create the links between pages like you normally would with HTML, except the framework will automatically handle the page request using Ajax when possible. This creates a seamless page transition and a quicker response time for mobile devices that may be on limited bandwidth. If Ajax isn’t possible, such as an external-domain URL or if the request to the page fails, a normal HTTP request for the page will be issued. There are also some special features that go along with links such as forcing a page refresh, setting up “back” buttons, creating email links that launch the mail client using the mailto: protocol and telephone links that initiate a call using the tel: protocol. Here are some examples:

A regular internal link:

<a href="../index.html">Link in the same domain</a>

Forcing the page to refresh and prohibit AJAX:

<a href="index.html" data-ajax="false">Link with refresh the page</a>

A link to send an email

<a href="mailto:me@foo.com">Basic email link</a>

Phone link:

<a href="tel:5555555555">Call me!</a>

When setting up your links you can also think about page transitions. The jQuery Mobile framework provides six CSS-based transitions that can be used on your site to create a more professional and polished result. Setting up these transitions is easy since it only requires adding the data-transition attribute to your links:

This link will use the slide transition:

<a href="../index.html" data-transition="slide">Link in the same domain</a>

This link will use the pop transition:

<a href="../index.html" data-transition="pop">Link in the same domain</a>

It’s that simple! You would now have a custom-looking transition between your pages that only took a second to add.

There are many more features, controls, documentation and examples at the jQuery Mobile home page at:

http://www.jquerymobile.com

You can also see examples of mobile sites that have been created using the framework if you need some inspiration. There are so many great reasons to use the jQuery Mobile framework and it is so easy to learn that you should get started today!

Posted by: Dhiraj kumar

Advertisements

9 Ways to Speed Up Your Web Pages with HTML5 & CSS3

Web designers/developers are always looking for new ways to improve the speed and performance of the pages. With some of the new features available in HTML5, there are several ways that you can improve your web applications/pages to give your user a better experience. We’ve compiled 9 easy-to-implement HTML5 tips and tricks here that would help you streamline your website without investing in additional infrastructure.

1. Use HTML5 Forms and Inputs

HTML5 has introduced a whole new set of form attributes and input types to upgrade your existing HTML forms. Not all browsers are supporting these yet, but for the ones that are there are some useful features built in.

  • autofocus focuses the caret on page load so you can begin typing in the field immediately
  • placeholder allows you to set default text in a field that will clear when the field is clicked
  • required will not let the form submit if the field is not filled out
  • pattern lets you specify a custom regular expression that the field must meet

Since these functions are now built-in, you will not need to create JavaScript functions to handle them. This will speed up your pages and create a more responsive feel to your page.

2. Use CSS Transitions

Using CSS transitions instead of JavaScript functions will greatly improve the speed of your pages as well as create an clean visual transition between two states. By using the totheleft andtotheright you can move a box around to create transitional movement. For example:

div.box {
    left:50px;
    //for webkit browsers
    -webkit-transition: all 0.3s ease-out;
    //for mozilla
    -moz-transition: all 0.3s ease-out;
    //for opera
    -o-transition: all 0.3s ease-out;
    //other browsers
    transition: all 0.3s ease-out;
}
div.box.totheleft {
    left0px;
}
div.box.totheright {
    left80px;
}

Since the number of bytes sent to the browser is much less when using CSS-based animations instead of JavaScript, the animation will be quicker and more responsive.

3. Use HTML5 Web Storage

When you need to store information such as in a cookie, you create an inefficient situation where the cookie data must be added to every HTTP request header. This ultimately makes a large impact on response time. Using HTML5, we can create a solution to this problem and store information in Web Storage instead of cookies.

Two Web Storage objects, sessionStorage and localStorage have been created to store persistent user data on the client-side for the length of the session. This data is not transferred through the HTTP request so it does not slow down the response time of the page. Here is a small example:

//check to see if localstorage is present (browser supports HTML5)
if (('localStorage' in window) && window.localStorage !== null) {
    //store items
    localStorage.wishlist = '["Bear", "Cow", "Pig"]';
}

As you can see, this method is much simpler than cookies since we do not need to specify an expiration or store the cookie with the document in the DOM.

4. Use Web Workers

Web Workers are part of the new HTML5 specification and are an API for running scripts in the background. This creates an almost multi-thread-like environment where large processing can happen in the background while normal page function can continue to function. When using a Web Worker, you just need to specify the script that the worker will be running, any event listeners (if any) and then start the worker. Here is an example:

var worker = new Worker('doWork.js');
worker.addEventListener('message'function(e) {
    console.log('Worker said: ', e.data);
}, false);
worker.postMessage('Hello World'); // Send data to our worker.

There are many situations where using Web Workers would create a much faster application environment such as image processing, text formatting or receiving and processing large files.

5. Use Web Sockets

Web Sockets is a specification for an API that allows for two-way communication with a remote host. This method can be used between a client and server application or can be implemented between web browsers and servers. Since Web Sockets has a very light-weight frame, the bandwidth consumption is much less and often creates a 35% reduction in bytes sent as well as ping times that are 3-5 times shorter than standard HTTP.

Not only can Web Sockets create faster communication, it can create a way for your application to work in limited environments. Since Web Sockets only run on port 80, they can be used as a way to get around blocked ports that your application may need.

6. Use Application Cache

Application caching creates a way for developers to have offline web sites and applications. This allows for offline browsing, reduced server loads and faster site speeds since some elements are cached. The developer can specify which files the browser should store in the cache manifest file, which is a simple text file of resources. Here is an example of a cache manifest file:

CACHE MANIFEST
# 2011-06-18:v3
# Explicitly cached entries
index.htm
style.css
# offline.htm will be displayed if the user is offline
FALLBACK:
/ /offline.htm

This manifest file references a “catch all” page that will be displayed if the user tries to access pages that are not cached while offline. Only the pages specified in the “cached entries” section will be available to the user. You must enable the page to use the application cache and point it to your manifest file. Here is how you reference the file:

<html manifest="http://www.example.com/example.appcache">
  ...
</html>

Manifest cache files can have any file extension but you need to be sure that your web server is setup to handle them with the correct MIME type. For example, in Apache:

AddType text/cache-manifest .appcache

Using the application cache you can create a viable, offline experience for your users with very little effort. When speeding up your pages, caching can be very helpful in creating less server traffic and caching the static items that you do not update often.

7. Use CSS Instead of Images

Using CSS effects instead of images can be an easy way to speed up your site and many popular image techniques can be replicated using CSS. Not only do you cut down on the number of bytes going through your server but you cut down on HTTP requests. Here are some great CSS techniques that you can use to cut down on the images your site is using:

  • CSS Masks
  • Box-shadow
  • Transforms
  • RGBA/Alpha opacity
  • Border-radius
  • Linear and radial gradients

8. Use Hardware Acceleration

While hardware acceleration may not be available in all browsers yet, it packs a big punch in those that support it. If your application uses animations or 3D transforms you can turn on hardware acceleration to get the GPU working for you. In order to use this feature you need to use a HTML5 canvas and your applications will instantly become twice as fast at rotations, scaling and opacity. These features will have the benefit of being handled directly by the GPU and won’t require a redraw of the layer contents.

9. Use Client-side Databases

Currently, the major browsers can’t agree on which client-side database to support but Web SQL Database and IndexedDB can be used to greatly improve the speed of data storage to the client-side instead of sending the data back to your server. Not only will this decrease HTTP requests but it will cut down on the load of your server when the user wants to do simple tasks like search, sort or filter.

Unfortunately, since most browsers support Web SQL DB and Mozilla only supports IndexedDB, you will either have to choose to support the two or cut out Mozilla users. However, both of them are simple to learn and use so it isn’t hard to begin using these to speed up the storage of data for your pages.

As you can see, there are many great new features in HTML5 that you can use to begin speeding up your web pages and create a better user experience for web applications. Getting started with HTML5 is easy and pays off with big benefits almost from the start. Get started by implementing some of these features in your sites and you will begin to see that there are great things ahead for your sites with HTML5.

Posted by: Dhiraj kumar

jQuery Basics Tutorial – How To Use jQuery & How jQuery Works?

jQuery: The Basics

This is a basic tutorial, designed to help you get started using jQuery. If you don’t have a test page set up yet, start by creating a new HTML page with the following contents:

<!doctype html>
<html>
  <head>
    <meta charset="utf-8">
    <title>Demo</title>
  </head>
  <body>
    <a href="http://jquery.com/">jQuery</a>
    <script src="jquery.js"></script>
    <script>

    </script>
  </body>
</html>

Edit the src attribute in the script tag to point to your copy of jquery.js. For example, if jquery.js is in the same directory as your HTML file, you can use:

 <script src="jquery.js"></script>

You can download your own copy of jQuery from the Downloading jQuery page

Launching Code on Document Ready

The first thing that most Javascript programmers end up doing is adding some code to their program, similar to this:

 window.onload = function(){ alert("welcome"); }

Inside of which is the code that you want to run right when the page is loaded. Problematically, however, the Javascript code isn’t run until all images are finished downloading (this includes banner ads). The reason for using window.onload in the first place is that the HTML ‘document’ isn’t finished loading yet, when you first try to run your code.

To circumvent both problems, jQuery has a simple statement that checks the document and waits until it’s ready to be manipulated, known as the ready event:

 $(document).ready(function(){
   // Your code here
 });

Inside the ready event, add a click handler to the link:

 $(document).ready(function(){
   $("a").click(function(event){ alert("Thanks for visiting!"); });
 });

Save your HTML file and reload the test page in your browser. Clicking the link on the page should make a browser’s alert pop-up, before leaving to go to the main jQuery page.

For click and most other events, you can prevent the default behaviour – here, following the link to jquery.com – by calling event.preventDefault() in the event handler:

 $(document).ready(function(){
   $("a").click(function(event){
     alert("As you can see, the link no longer took you to jquery.com");
     event.preventDefault();
   });
 });

Complete Example

The following is an example of what the complete HTML file might look like if you were to use the script in your own file. Note that it links to Google’s CDN to load the jQuery core file. Also, while the custom script is included in the <head>, it is generally preferable to place it in a separate file and refer that file with the script element’s src attribute

 <!DOCTYPE html>
 <html lang="en">
 <head>
   <meta charset="utf-8">
   <title>jQuery demo</title>
 </head>
 <body>
   <a href="http://jquery.com/">jQuery</a>
   <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5/jquery.min.js"></script>
   <script>
     $(document).ready(function(){
       $("a").click(function(event){
         alert("As you can see, the link no longer took you to jquery.com");
         event.preventDefault();
       });
     });
   </script>
 </body>
 </html>

Adding and Removing an HTML Class

Important: The remaining jQuery examples will need to be placed inside the ready event so that they are executed when the document is ready to be worked on. See Launching Code on Document Ready above for details.

Another common task is adding (or removing) a class.

First, add some style information into the <head> of your document, like this:

 <style>
    a.test { font-weight: bold; }
 </style>

Next, add the addClass call to your script:

  $("a").addClass("test");

All your a elements will now be bold.

To remove the class, use removeClass

 $("a").removeClass("test");
  • (HTML allows multiple classes to be added to an element.)

Special Effects

In jQuery, a couple of handy effects are provided, to really make your web site stand out. To put this to the test, change the click that you added earlier to this:

 $("a").click(function(event){
   event.preventDefault();
   $(this).hide("slow");
 });

Now, if you click any link, it should make itself slowly disappear.

CALLBACK AND FUNCTIONS

A callback is a function that is passed as an argument to another function and is executed after its parent function has completed. The special thing about a callback is that functions that appear after the “parent” can execute before the callback executes. Another important thing to know is how to properly pass the callback. This is where I have often forgotten the proper syntax.

Callback without arguments

For a callback with no arguments you pass it like this:

 $.get('myhtmlpage.html', myCallBack);

Note that the second parameter here is simply the function name (but not as a string and without parentheses). Functions in Javascript are ‘First class citizens’ and so can be passed around like variable references and executed at a later time.

Callback with arguments

“What do you do if you have arguments that you want to pass?”, you might ask yourself.

Wrong

The Wrong Way (will not work!)

 $.get('myhtmlpage.html', myCallBack(param1, param2));

This will not work because it calls

myCallBack(param1, param2)

and then passes the return value as the second parameter to $.get()

Right

The problem with the above example is that myCallBack(param1, param2) is evaluated before being passed as a function. Javascript and by extension jQuery expects a function pointer in cases like these. I.E. setTimeout function.

In the below usage, an anonymous function is created (just a block of statements) and is registered as the callback function. Note the use of ‘function(){‘. The anonymous function does exactly one thing: calls myCallBack, with the values of param1 and param2 in the outer scope.

$.get('myhtmlpage.html', function(){
  myCallBack(param1, param2);
});

param1 and param2 are evaluated as a callback when the ‘$.get’ is done getting the page.

A basic introduction to jQuery and the concepts that you need to know to use it.

Posted by: Dhiraj kumar

Tutorials : Introducing $(document).ready()

jQuery

This is the first thing to learn about jQuery: If you want an event to work on your page, you should call it inside the $(document).ready() function. Everything inside it will load as soon as the DOM is loaded and before the page contents are loaded.

 $(document).ready(function() { // put all your jQuery goodness in here. });

The $(document).ready() function has a ton of advantages over other ways of getting events to work. First of all, you don’t have to put any “behavioral” markup in the HTML. You can separate all of your JavaScript/jQuery into a separate file where it’s easier to maintain and where it can stay out of the way of the content. I never did like seeing all those “javascript:void()” messages in the status bar when I would hover over a link. That’s what happens when you attach the event directly inside an <a href> tag.

On some pages that use traditional JavaScript, you’ll see an “onload” attribute in the <body> tag. The problem with this is that it’s limited to only one function. Oh yeah, and it adds “behavioral” markup to the content again. Jeremy Keith’s excellent book, DOM Scripting, showed me how to create an addLoadEvent function to a separate JavaScript file that allows for multiple functions to be loaded inside it. But it requires a fair amount of code for something that should be rather straightforward. Also, it triggers those events when the window loads, which leads me to another advantage of $(document).ready().

With $(document).ready(), you can get your events to load or fire or whatever you want them to do before the window loads. Everything that you stick inside its brackets is ready to go at the earliest possible moment — as soon as the DOM is registered by the browser, which allows for some nice hiding and showing effects and other stuff immediately when the user first sees the page elements.

Posted by: Dhiraj kumar

10 Tips for Writing Awesome jQuery Plugins

Introduction

I’ve been developing and studying plugins, particularly in jQuery for quite sometime and through this process I have learned a lot about what works and what doesn’t work. There are a ton of great plugins out there that look great on the surface but are sometimes very frustrating to work with behind the scenes. So many plugins if only had a little extra effort could be taken from good to great and become much more widely used.

These are some simple tips that I have put together that will help any developer write truly great plugins. There are some things that may not seem quite as obvious at first, but they are there not only to develop your jQuery plugins, but to help maintain and expand on them in the future as well.

It is also important to note that having a solid structure and guideline to follow for you plugin speeds up development significantly as it takes away any time required to think about how you should start your project. You will already know and will only need to write the core code of your plugin and not worry about any of the other details.

1. Plugins Should Work Out of the Box

This is my biggest frustration when using plugins out there so I have made it the first point. Your plugin should just work, there should be no extra setup or structure to define. There should at the minimum be a basic default that just works and should not require anything more than an initialization.

$("#container").DG_Tooltip();

A good example would be a jQuery slideshow plugin that has an interface for slides and a next/prev button. I’ve seen plugins that will ask you to set up a div with a proper id and class and then ask you to reference it through the plugin function. Things like this should be built in directly and should be provided as options that can be toggled on or off.

2. Always Provide Default Settings

It will be quite rare that your plugin will contain absolutely no configurable settings. This follows from the first point as you should always try to find as many settings as you can and provide a set of defaults for them as well. This will definitely increase the chances of any developer using your plugin and increases that chance that they will spread the word about it.

var defaultSettings = {
    mode            : 'Pencil',
    lineWidthMin    : '0',
    lineWidthMax    : '10',
    lineWidth       : '2'
};
settings = $.extend({}, defaultSettings, settings || {});

The code above is the standard way to set your default settings and extend them with any settings developers may pass in.

3. Keep All Naming Unique

When creating your plugin you should always be mindful of keeping any reference to the plugin absolutely unique. This goes for classes, ids and the plugins name itself. This requires absolutely no extra effort and will ensure that you avoid any conflicts with existing JavaScript and CSS code.

$("#container").tooltip();     //bad    
$("#container").DG_Tooltip();   //good

In the above example we keep the name unique for our plugin by prepending it with a “DG_” to differentiate it from any generic names that might otherwise exist. I also follow this unique naming convention with the CSS and will make sure even generic terms like “tab” or “holder” all contain the keyword.

DG_Paint_button
DG_Paint_holder

I also like to add the underscore just to make sure there is no chance of any id or class name conflicts, giving me more confidence that my jQuery plugin will succeed.

4. The Standard Plugin Layout in a Nutshell

This is a pretty standard piece of jQuery code that you will see most good plugins having, it has all the important pieces you will need for developing, maintaining and updating your plugin. Following a structure takes away a lot of the guess work and lets you focus on developing the plugin.

var defaultSettings = {
    //settings
};
$.fn.DG_Paint = function(settings)
{
    //check for setters/getters
    
    return this.each(function()
    {
        var elem = $(this);
        //run some code here
        
        elem.data("DG_Paint", DG_Paint);
    }
    //classes/prototyping
}

There are five key points to note here:

  1. Default settings go outside of the plugin, it does not need to be instantiated each time.
  2. Setters and getters aren’t always required but should be checked for before running the main each loop.
  3. Return each element to not disrupt the jQuery method chaining flow.
  4. Store any data for the element using .data(), we may need this later for setters and getters.
  5. Finally setup any Classes/Prototypes outside and after the main loop.

5. Keep Your Code Organized

Although this one seems quite obvious I will quickly run through it as I have seen some odd setups in far too many plugins. It’s always a good idea to keep a simple file structure for your files that is self explanatory.

./images/
./includes/
./themes/
./DG_Paint.js
./DG_Paint.min.js
./DG_Paint.css
./DG_Paint.min.css

It’s quite clear with the following setup, which files need to be included and where I can find other plugin files or jQuery libraries should I need to take a look at them.

6. Use Class Prototyping

This is a pretty big topic on it’s own so I will only briefly mention it here. Basically there are two main reasons for prototyping your functions.

  1. Not having to instantiate a separate copy of each method is much more efficient and runs faster.
  2. It saves a ton of memory by only having references to each object method and not having a copy of each one.
function Canvas(settings)
{
    this.canvas = null;     
    this.ctx = null;
}
Canvas.prototype = 
{
    generate: function()
    {
        //generate code
    }
}

It also serves to organize your code and makes it much more reusable. In the above example only the Canvas object gets instantiated for each new object while the prototyped functions are only referenced.

7. Provide Setters and Getters

Providing setters and getters is not a requirement but I find it’s a good option to provide your developers should they need it. All we’re doing here is allowing modifications to the plugin after it has been called. The most basic setup follows:

if(typeof option === 'object'){
    settings = option;
}else if(typeof option === 'string'){
    if(
        this.data('DG_Paint_canvas') &&
        defaultSettings[option] !== undefined
    ){
        var canvas = this.data('DG_Paint_canvas');
        if(settings){
            canvas.settings[option] = settings;
            return true;
        }else{
            return canvas.settings[option];
        }
    }else return false;
}

All we’re doing here is checking if an option is set rather than some settings. If two parameters are provided it means we are setting, if one parameter is set it means we are requesting the specified option.

8. Test in All Browsers

This is absolutely crucial for the survival of your plugin. Developers may not catch glitches in your code, but their users most certainly will and if there are a lot of complaints that lead back to your plugin it will simply be replaced.

This step can always be tiring as after completing a plugin you feel you just want to launch it. Make sure you always hold back on this urge and spend the extra day to test your plugin thoroughly with as many scenarios as you can think of. This will not only fix up any simple bugs but also may shine some light on some simple improvements.

9. Packaging for Release

Once your plugin is all polished and ready for release take the time to do the next three simple steps.

  1. Write some documentation for the trickier parts, not only for other developers that may be looking at your code but for yourself as well.
  2. Version your plugin either by the file names or in the documentation somewhere. It doesn’t matter where as long as developers can see what version they are using and check for updates.
  3. Finally provide minified versions of your code, this only takes a few minutes and adding it will make developers using your plugin happy and coming back for more.

Sometimes it’s the simple steps that can really make a difference, in the end the developers will make or break your jQuery plugin so make sure you keep them as happy as possible.

10. Upload Your Plugin

There are plenty of services out there for this, but two I prefer are Github and Google code.

You man not always want to upload your jQuery plugins for public use, especially if it’s an internal project for work, but likewise keep your plugins in their own repository and outside of the main codebase. This ensures your plugins get maintained with proper versioning and documentation.

However if your plugin is indeed for public use, services as the above mentioned Github and Google code are fantastic as they provide areas for issue reporting, activity feeds and download counters.

This lets you interact with the users of your plugin to see how well your plugin is doing from a total downloads point of view. These services are extremely easy to setup and provide a lot of value.

Conclusion

Following these tips should pretty much cover the core of your jQuery plugin lifecycle. It also provides a more standard format for you to follow as well as providing a familiar strucure that developers are used to. Wheter you are developing plugins for fun or profesionally the more your plugin gets used the more gratifying it feels.

Posted by: Dhiraj kumar