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 a tasklist


Now that we have the basics under our belt let's get started on the tasklist application. We'll call our application Task at Hand, or Task@Hand to be hip. First make a copy of our template folder and rename it to taskAtHand. Also rename the .html, .css, and .js files to taskAtHand. Now we're ready to start our first HTML5 application. You can find the code for this section in Chapter 1/example1.1.

The first thing we need to do is go into the HTML file and change the title and names of the CSS and JS files in the <head> element to taskAtHand:

<head>
  <title>Task@Hand</title>
  <link href="taskAtHand.css" rel="StyleSheet" />
  <script src="lib/jquery-1.8.1.min.js"></script>
  <script src="taskAtHand.js"></script>
</head>

Next we move on to the body. First we change the name of the application in the <header> element. Then go into the <div id="app"> element and add a text input field where the user can type in the name of a task. Finally, we add an empty list to hold our list of tasks. Since we are building a list we will use the unordered list <ul> element.

<body>
  <div id="app">
    <header>Task@Hand</header>
    <div id="main">
      <div id="add-task">
        <label for="new-task-name">Add a task</label>
        <input type="text" id="new-task-name" title="Enter a task name" placeholder="Enter a task name"/>
      </div>
      <ul id="task-list">
      </ul>
    </div>
    <footer>
    </footer>
  </div>
</body>

That's all of the markup we need for now. There is one thing to point out in here, that's new to HTML5. There is a new attribute for inputs called placeholder that displays some text in the field until the user starts typing something. This gives the user a hint as to what they should enter in the field. It is valid for input elements that allow the user to enter text.

Let's go into the JavaScript file and get coding. The first thing we'll do is rename the application object to TaskAtHandApp:

function TaskAtHandApp()
{
    // code not shown…
}
$(function() {
    window.app = new TaskAtHandApp();
    window.app.start();
});

Note

A standard in JavaScript is that only things that require a new statement (that is, object constructors) should start with a capital letter. This helps to distinguish what requires the new keyword to be created. Everything else, including variable and function names, should start with a lowercase letter.

When the user is done typing in a task name and hits the Enter key, we want to create a new list item element and add it to the list. The first thing we need to do is add an event handler to the text field so we get notified when a key is pressed. We will add this in the start() method of our application object:

this.start = function()
{
    $("#new-task-name").keypress(function(e) {
        if (e.which == 13) // Enter key
        {
            addTask();
            return false;
        }
    })
    .focus();
        
    $("#app header").append(version);
    setStatus("ready");
};

First we get the text field by doing a jQuery select on its ID, new-task-name. Then we add a keypress() event handler to that element passing in a function to execute every time the event is triggered. jQuery passes one parameter to the event handler function, which is a keypress event object. The event object contains a field named which that contains the character code of the key that was pressed. The one we are interested in here is the Enter key, which has a code of 13.

When the user presses the Enter key we call the addTask() method (defined next), and then it returns false. The reason we return false here is to tell the system that we handled the key press event, and don't want it to do the default action. Some browsers will perform other actions when the Enter key is pressed.

Next, we add another function call onto the end of the keypress() handler to set the focus back to the text field. At this point you're probably asking yourself, how does that work, calling a function on a function? This is called function chaining and is perhaps one of the most useful features of jQuery. Most of jQuery's methods return a pointer to the object itself, so we can perform multiple actions in a single line of code.

Now we'll write that addTask() method. This method will get the name of the task and add a new list item to the <ul> element in our HTML:

function addTask()
{
    var taskName = $("#new-task-name").val();
    if (taskName)
    {
        addTaskElement(taskName);
        // Reset the text field
        $("#new-task-name").val("").focus();
    }
}
function addTaskElement(taskName)
{
    var $task = $("<li></li>");
    $task.text(taskName);
    $("#task-list").append($task);
}

First we get the value of the new-task-name text field using jQuery's val() method, which is used to get the value of input fields. Just to make sure the user actually typed something in, we test that the taskName variable is "truthy", which in this case means it's not an empty string.

Next we call the addTaskElement() method. There we create a new <li> element. You can create a new element by passing in an element definition instead of select to jQuery. In this case we use "<li></li>" to create a new empty list item element, and then assign it to the $task variable. Then, we immediately fill that element with the task name using the text() method.

Note

When assigning a jQuery object to a variable, it's a good practice to start the variable name with $, so you know that it references a jQuery object.

Now that we have the new element we need to add it to the document in the correct place, which is inside the <ul id="task-list"> element. That is done by selecting the task-list element and calling the append() method. This adds our new <li> element to the end of the tasklist.

The last thing we do, back in the addTask() method, is clear out the value of the text input field and set the focus back on it so the user can immediately enter another task. We use function chaining here to do both in one statement. Notice that we used the jQuery val() method for both setting and getting the value of the text field. If you pass a value in, it sets the control's value; otherwise it returns the control's value. You'll find that a lot of the jQuery methods work this way. For example, the text() method will either set the text within an element, or return it if no value is passed in.

What just happened?

We created a tasklist application where the user can type in task names and build a list of tasks. Let's open the application in our browser and see what we've got so far: