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 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:

What just happened?
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