Book Image

HTML5 Web Application Development By Example : Beginner's guide

By : Jody Gustafson
Book Image

HTML5 Web Application Development By Example : Beginner's guide

By: Jody Gustafson

Overview of this book

HTML5's new features have made it a real application development platform with widespread adoption throughout the industry for this purpose. Being able to create one application that can run on virtually any device from phone to desktop has made it the first choice among developers. Although JavaScript has been around for a while now, it wasn't until the introduction of HTML5 that we have been able to create dynamic, feature-rich applications rivaling those written for the desktop. HTML5 Web Application Development By Example will give you the knowledge you need to build rich, interactive web applications from the ground up, incorporating the most popular HTML5 and CSS3 features available right now. This book is full of tips, tools, and example applications that will get you started writing your own applications today. HTML5 Web Application Development By Example shows you how to write web applications using the most popular HTML5 and CSS3 features. This book is a practical, hands-on guide with numerous real-world and relevant examples. You will learn how to use local storage to save an application's state and incorporate CSS3 to make it look great. You will also learn how to use custom data attributes to implement data binding. We'll use the new Canvas API to create a drawing application, then use the Audio API to create a virtual piano, before turning it all into a game. The time to start using HTML5 is now. And HTML5 Web Application Development by Example will give you the tips and know-how to get started.
Table of Contents (18 chapters)
HTML5 Web Application Development By Example Beginner's guide
Credits
About the Author
About the Reviewer
www.PacktPub.com
Preface
Index

Time for action – creating the JavaScript file


Let's move on to the JavaScript file, app.js. Here we'll stub out a basic outline for our application template. If you don't know what the dollar signs are for, they are aliases for the jQuery library. We'll go over some jQuery basics in a moment.

"use strict";

function MyApp()
{
    var version = "v1.0";

    function setStatus(message)
    {
        $("#app>footer").text(message);
    }
    
    this.start = function()
    {
        $("#app>header").append(version);
        setStatus("ready");
    };
}

Starting at the top we will include "use strict" in our JavaScript files. This informs the JavaScript runtime to use newer and stricter standards when running our code. For example, in older versions of JavaScript it was completely legal to use a variable name without declaring it first using the var keyword. This had the side effect of making it a global variable attached to the window object. When "use strict" is defined, you will get an error if you try to do that. It helps you find bad coding mistakes that could lead to bugs in your program.

Note

If you are using some older JavaScript library that doesn't work in strict mode you can add "use strict" inside of function declarations instead, to make only that block of code use strict mode.

function strict()
{
    "use strict";
    // Everything inside here will use strict
// mode
}

Next we define the main application object, myApp. There are many ways to define an object in JavaScript, including using object literals and constructor functions. Object literals are the simplest way to define an object, but those objects are created as soon as the JavaScript is loaded, usually before the DOM is ready. Here's what our object would look like as an object literal:

var myApp = {
    version: "v1.0",
    setStatus: function(message)
    {
        $("#app>footer").text(message);
    },
    start: function()
    {
        $("#app>header").append(this.version);
        this.setStatus("ready");
    };
};

Since our applications are manipulating the Document Object Model (DOM), we don't want to create the object until the DOM is ready. That's why we will be using the function constructor form for creating an object.

The DOM, or Document Object Model, is the internal representation of the HTML markup. It's a hierarchical tree of objects that represents the HTML elements.

Another problem with using object literals is that everything defined in it is a member of the object, and therefore must be accessed using the this keyword. Notice in the preceding object literal form how we must use this to access version and setStatus(). However, when creating an object using a constructor, we can define functions and variables inside of the constructor without making them members of the object. Since they aren't members, you don't have to use the this keyword to access them.

So what's wrong with using this? After you've programmed in JavaScript for a while, you become aware that the this keyword can cause a lot of confusion because it can mean different things at different times. In other languages, such as C# and Java, this always points to the object that you are inside of. In JavaScript, this is a pointer to the object that called the function, which for event handlers is usually the window object. So the more we avoid using it, the better.

Another advantage of using a constructor is being able to define private and public methods. Notice that the setStatus() method is defined using a normal function declaration. This will make it a private method that can only be accessed from within the object that encloses it, and doesn't require using this to call it. The start() method, on the other hand, is assigned to the object using this. That will make start() a public method that can only be accessed from an instance of the object. We will use this paradigm throughout our JavaScript to implement the private and public members of our objects.

The last thing we need is a document-ready event handler. The document-ready event gets fired once the page has loaded and the DOM hierarchy has been fully constructed. There are two ways to add this event handler using jQuery. The first and more verbose way is what you would expect:

$(document).ready(handler);

However, since it is probably the most basic and important event you will need to implement, jQuery provides a shorthand form that is as simple as it gets:

$(handler);

Here is our document-ready event handler:

$(function() {
    window.app = new MyApp();
    window.app.start();
});

This is an important piece of code. It defines the starting point for our application. It is equivalent to the main() function in other languages, such as C, C++, C#, and Java.

Here we create an instance of our main application object, and then assign it to a global variable named app by attaching it to the window object. We make it global so it can be accessed throughout our application. Last but not least we call the start() method of our application object to get the application going.

What just happened?

We just created a template that we can use to start writing new applications with minimal startup time. It consists of HTML, CSS, and JavaScript files. At this point our template is finished, and we have the basics we will need to start writing new HTML5 applications.

The dollar sign identifier

You may have noticed dollar signs everywhere in our JavaScript code. The dollar sign is no more than an alias for the jQuery object. You could replace all dollar signs with jQuery and it would be the same, just more typing. If you already know about jQuery you might want to jump ahead. Otherwise I'll give a brief overview of jQuery.

jQuery is a popular JavaScript library that at its most basic level provides functions to access and manipulate the DOM. It also provides a lot of other useful functionality, such as event handling, animations, and AJAX support. In addition, it hides many of the different quirks between browsers, so you can concentrate on programming and not on how to make your code work in every browser. It makes writing JavaScript applications tolerable, and dare I say fun. I wouldn't think of writing an HTML5 application without it. It's to JavaScript what the System library is to Java and C#.

For the most part, jQuery uses the same query syntax as CSS to select elements. The typical pattern is to select one or more elements and then perform some action on them, or retrieve data from them. So, for example, here is a jQuery select to get all div elements in the DOM:

$("div")

The following query would give you the element that has an ID of main:

$("#main")

Just like CSS, the hash sign selects elements with a specific ID, and a dot selects elements that have a specific class. You can also use compound search criteria. This next query would return all of the elements that are descendants of the element with an ID of main and have a class of selected:

$(#main .selected")

After you have selected one or more elements you can perform some action on them. A jQuery select returns a jQuery object that is like an array, but also has lots of built-in functions to do all sorts of things, which we will learn about as we progress through this book. For example, the following line of code would hide all of the elements returned from the previous select (set their CSS display attribute to none):

$(#main .selected").hide()

Simple and powerful. So what is the deal with the dollar sign anyway? Some people assumed it was some sort of magic that jQuery could use the dollar sign as an alias. But apparently the dollar sign is a valid character to start a variable or function name within JavaScript.