01219245/javascript1/tutorial2

จาก Theory Wiki
ไปยังการนำทาง ไปยังการค้นหา
This is part of 01219245

While the sequential-style interaction as in our previous tutorial is easy to write, the pop-ups is not a nice way to interact with users. Most UI application uses another programming model, called event-driven programming. In this tutorial, we shall learn how to do that in JavaScript. While event-driven programming is easy to do in JavaScript, it will be more entertaining to use a famous jQuery library to simplify various tasks.

This time we will not use jsFiddle, but we will write an easy web-application in your laptop/notebook/pc. We will also use Git to keep track of our development.

To help you to get familiar with Git, we will commit a lot in this tutorial. In real project we will commit when we make some "unit" of changes and might not commit as often as in this tutorial.

The plan

In this tutorial, we will re-implement the number guessing game we did previously so that it works like a typical web application.

The game should look like this:

Guess-ui.png

From that, let's think a bit about what we have to do (or have to learn how to do).

Think

Don't read further until you have thought carefully about the above question.

Steps

What we have to do:

  • Read a guess from the user.
    • If we look more carefully into this step, we have to wait until the user press the button, then take the number in the text box.
  • Check the guess.
  • Update the result.

In GUI application, there are many "pieces" of the UI that the user can interact. For example, in the application above, if we want to add another button, called "Clear", that clear the text input, the user can either press the "Guess" button or the "Clear" button. It is hard for usual sequential program that waits for the user input to deal with many things at the same time. A better way to deal with these kinds of application is to think about the events that can occur and write programs that handle them. This is the idea of an event-driven programming.

First try at event-driven programming and jQuery

In this section, we shall experiment with the concepts and tools that we will use to re-write our number guessing game, namely, event-driven programming and jQuery.

Create a new directory called guessingprep. Create a new Git repository there.

Let's create an empty web page with a button. Create a file index.html with the following:

<!doctype html>
<html lang="en">
<body>
  <button>Click me!</button>
</body>
</html>

View the page on a browser. (Note: enter file:/// into the URL bar, and keep browsing.) You should see the button. Clicking at it won't make anything happens.

Right now, it's a nice place to commit our changes to the Git repository.

git add index.html
git commit -m "an empty page with a button"

Let's add a simple interaction. An onclick (from on click) attribute at a button element specify a JavaScript code that should be executed if the button is clicked. Change the button line to:

 <button onclick="alert('Hello!');">Click me!</button>

Reload the page, and try clicking at the button.

Let's commit again. Put your own commit message.

git commit -am "________________________________"

Later on, I'll signal you where you should commit, you must add the commit message by yourself.

Including JavaScript in a web page

If we want to do complex things when a button is clicked, placing all the code in the onclick attribute is a mess. We shall write a function to do the work, and just call the function inside the onclick attribute.

There are two ways to include the JavaScript code in a web page. We can write a JavaScript code in a file and place a link to that file in our html page. We can also put the code directly inside the html page; this is call inline JavaScript. We shall write an inline JavaScript code for now.

A JavaScript code is placed inside a script block. Change index.html to the following:

<!doctype html>
<html lang="en">
<body>
  <button onclick="update();">Click me!</button>

<script type="text/javascript">
var c = 0;
function update() {
  c++;
  alert(c);
}
</script>
</body>
</html>

Note a weird indentation. To help writing JavaScript code better, I remove one-step of indentation from the script block.

You should click to play with it, if it works, commit the change.

You can add onclick attributes to buttons, links, and many elements. If we have to do that for many elements in the web page, it can be very messy. jQuery has a nice way we can deal with this mess.

Using jQuery

jQuery is a wonderful library that facilitates many tasks in JavaScript.

Go to jQuery's homepage, go to its download page, and download the compressed, production jQuery. While the filename should look like jquery-1.X.X.min.js, save the jquery script as jquery.js.

To include the library into our web page, add the following line

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

before our previous script block. This is how you include an external JavaScript to an html page.

With jQuery, instead of attaching the onclick attribute to the DOM elements, we will add the handler to the elements in the JavaScript source.

NOTES: We usually calls the elements in an HTML page a DOM element, where DOM stands for Document Object Model.

Selectors

What jQuery provides us is a function $. (You are right; the function name is just a dollar sign.) This function is used to query the DOM elements so that we can work on them. Let's see that by examples.

Let's remove the onclick attribute from the button, and add a line:

$("button").click(update);

to the end of the script block.

The complete index.html should look like this:

<!doctype html>
<html lang="en">
<body>
  <button>Click me!</button>

<script src="jquery.js"></script>
<script type="text/javascript">
var c = 0;
function update() {
  c++;
  alert(c);
}
$("button").click(update);
</script>
</body>
</html>

The weird statement we have just added falls into a common idiom for using jQuery:

$(selector).dosomething().dosomethingmore().dosomethingfurthermore();

The selector button selects all button elements in the page. The .click(update); part registers function update to the onclick event.

Try the code, and commit the current changes.

Two buttons: id and class

Let's add another button. Add the following line after the first button:

<button>Don't click me</button>

Before actually trying, what do you think will happen if you click this new button? Will the alert box appear? Why?

Now, let's try it. Do you know why?

If we don't want function update to run when the second button is clicked, we should selects only the first button when registering the click event. Right now the two buttons look pretty much the same; therefore, selecting with just button gives you both.

We can add more information to the DOM element,



Ready

Modifying texts

Let's write our game