Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Conferences
Free Learning
Arrow right icon
Arrow up icon
GO TO TOP
HTML5 Web Application Development By Example : Beginner's guide

You're reading from   HTML5 Web Application Development By Example : Beginner's guide Learn how to write rich, interactive web applications using HTML5 and CSS3 through real-world examples. In a world of proliferating platforms and devices, being able to create your own ‚Äúgo-anywhere‚Äù applications gives you a significant advantage.

Arrow left icon
Product type Paperback
Published in Jun 2013
Publisher Packt
ISBN-13 9781849695947
Length 276 pages
Edition 1st Edition
Languages
Tools
Arrow right icon
Author (1):
Arrow left icon
Jody Gustafson Jody Gustafson
Author Profile Icon Jody Gustafson
Jody Gustafson
Arrow right icon
View More author details
Toc

Table of Contents (13) Chapters Close

Preface 1. The Task at Hand FREE CHAPTER 2. Let's Get Stylish 3. The Devil is in the Details 4. A Blank Canvas 5. Not So Blank Canvas 6. Piano Man 7. Piano Hero 8. A Change in the Weather 9. Web Workers Unite 10. Releasing an App into the Wild A. Pop Quiz Answers 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.

You have been reading a chapter from
HTML5 Web Application Development By Example : Beginner's guide
Published in: Jun 2013
Publisher: Packt
ISBN-13: 9781849695947
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $19.99/month. Cancel anytime
Banner background image