Chapter 12

Making It Functional

Functions are the building blocks of JavaScript programs. They help you to keep from having to repeat yourself, and they make your programs neater and more flexible!

In this chapter, we use functions to create a game called Function Junction.

image

Understanding Functions

Functions are programs inside of programs. Functions are great at handling tasks that may be required multiple times by different parts of a program. They’re also a great way to keep things organized within your program.

Built-in functions

Some functions are built into JavaScript, such as the methods of arrays, strings, numbers, and other objects. You can tell that something’s a function because it has parentheses after it.

When a function is part of an object (such as the document object, for example) we call it a method. But it’s still a function.

Here are some of the functions that are built into JavaScript that you’ve already used:

getElementById()

toString()

addEventListener()

indexOf()

Can you think of other functions you’ve seen?

Custom functions

In addition to the functions that are built into JavaScript, you can also create your own, using the steps and information that we’re about to show you!

remember You can’t spell function without “fun,” and you can’t write JavaScript code without using functions. Therefore, you can’t write JavaScript code without having fun!

If you’ve read through the previous chapters, you’ve already seen functions in action in the demonstration programs. Here’s an example of a function that adds a smiley face to any text you give it:

function smileyIt(theText) {

  theText += " :)";

  return theText;

}

Follow these steps to try out this function:

  1. Open JSFiddle.net in your web browser.

    You should have a blank project. If it’s not blank, click the JSFiddle logo in the upper-left corner of the screen.

  2. Type the code for the smileyIt() function into the JavaScript pane.
  3. Click the Run button.

    Notice that nothing happens. Unlike JavaScript code that’s outside a function, code inside functions doesn’t run until the function is called.

  4. Add the following statement underneath the function:

    smileyIt("Hi There!");

  5. Click the Run link.

    Once again, nothing appears to have happened. But this time, something actually did happen. We just didn’t report the results of running the function back to you.

  6. Modify the statement you wrote in the last step to put the result of running the function into an alert popup, like this:

    alert(smileyIt("Hi there!"));

  7. Click the Run link.

    If you entered everything correctly, you should get an alert popup saying Hi there! :), as shown in Figure 12-1.

image

Figure 12-1: Outputting the result of the function to an alert.

tip alert() is another example of a built-in JavaScript function!

Knowing What Functions Are Made Of

Functions have a special vocabulary and way that they must be written and used. To really understand functions, you need to be able to speak their language. So, let’s look at a couple words and take apart a function to see what’s inside!

Defining a function

When you write a function, that’s called defining it. Defining a function makes the code inside that function available to be run.

There are a couple different ways to define a function. The most common way is to use the function keyword, followed by the name of the function, followed by parentheses and then curly braces, like this:

function myFunction() {

  // statements go here

}

Another way to define a function is by using the new Function technique. That looks like this:

var myFunction = new Function() {

  // statements go here

}

Both methods get the job done, but we recommend using the first, more common, technique.

Giving the function a head

The first part of a function definition is called the function head. The function head includes the function keyword, the name of the function, and the parentheses:

function myFunction()

Filling out the function body

Next up is the function body. The function body is made up of statements, surrounded by curly braces. For example:

{

  // this is the function body

}

Calling a function

When you run the code within a function body, that’s called calling the function. To call a function, you simply write the name of the function, followed by parentheses. For example:

myFunction();

Defining parameters

Parameters are values that can be included between the parentheses when a function is called. To define a parameter, simply give the parameter a name and put it between the parentheses in the function definition. For example:

function myFunction(theText) {

}

You can define multiple parameters by separating them with commas.

Passing arguments

When you call a function using a value between the parentheses, it’s called passing an argument. For example:

myFunction("This is some text");

In this case, the argument is the string "This is some text".

remember When you’re defining a function, the values between the parentheses are called parameters. When passing values into a function, they’re called arguments.

When you pass an argument into a function, the function automatically creates a new variable with the name of the parameter and gives it the value of the argument that you passed.

Returning a value

When you call a function and (optionally) pass it an argument, the function starts doing its thing. After the function completes its task, it stops running and produces some sort of value. The value that a function produces when it finishes running is called its return value.

You can set what the return value is by using the return statement. For example, the following function will always return the number 3000:

function whatsTheNumber(){

  return 3000;

}

To find out or use the return value of a function, you can call the function as part of an operation. For example, to do math with the result of a function, you just include the function as a normal operand (see Chapter 8), like this:

var theTotal = whatsTheNumber() + 80;

When you run this statement, a value equal to the return value of whatsTheNumber() plus 80 (or 3080) will be assigned to theTotal.

If you don’t specify a return value for a function, the function will return undefined.

Building Function Junction

Now that you know the basics of how functions are created and used, let’s write a game. We call this game Function Junction. The goal is to get a train as far along a track as quickly as possible without it crashing at the end of the track.

Before we explain how it works and show you how to build it, let’s try it out!

  1. Open your web browser and go to http://jsfiddle.net/user/forkids/fiddles.
  2. Find the program named “Chapter 12 – Function Junction” program in our public dashboard and click the title to open it.

To play the game, click the train. It starts moving down the track at a very slow pace. If you click the train again, it picks up a little bit of speed. Click several more times and it picks up even more steam. But if you keep clicking, the train will eventually be moving so fast that you’ll feel like you’re going off the rails on this crazy train.

If you don’t do something before the train reaches the end of the track, it will crash. All you need to do to bring the train to a screeching halt is to click the Stop button. But can you get to it quickly enough?!

technicalstuff Like so many computer games, the actual game play isn’t nearly as exciting as the narrative description. But with the skills you learn in this chapter, you’ll be able to make improvements and maybe even turn Function Junction into the next big thing!

Now, let’s see how to build Function Junction.

Start by going to our partially built version of the program, named “Chapter 12 – Function Junction – Start.” You can find it in our public dashboard in JSFiddle.

When you’ve located it and opened it, follow these steps:

  1. Click the Fork button to create your own copy of the program.
  2. Open the Fiddle Options and change the name of your new program.
  3. Click Update and then Set as Base to save your program.

Now we’re ready to get started!

Touring the HTML

The HTML for Function Junction is pretty simple, and we’ve included everything you need already.

Tiptoeing through the CSS

Now let’s move on to the CSS pane. We’ve already included all the CSS you need for the game. Before we show you that, take a look at Figure 12-2. This is what the game looks like without any CSS.

image

Figure 12-2: Function Junction without any CSS.

Pretty big difference, huh? Listing 12-1 shows all the styles that we apply to the game to make it look the way it does.

Listing 12-1 The Function Junction CSS

body {

    font-family: Arial, sans-serif;

}

#container {

    padding: 10px;

    width: 360px;

    height: 80%;

    background-color: #00FF00;

}

#track {

    width: 340px;

    border-top: 2px solid white;

    border-bottom: 2px solid white;

    margin: 20px auto;

}

#train {

    height: 92px;

    width: 100px;

    position: relative;

    left: 0px;

}

#stopButton {

    padding-top: 15px;

    margin: 10px auto;

    background-color: white;

    width: 100px;

    height: 50px;

    color: red;

    text-align: center;

    font-size: 24px;

    line-height: 30px;

}

Take a look at each of the selectors. Notice that, except for the font-family style that we’ve applied to the body element, we’re using all ID selectors, which begin with #.

We used most of these same styles in previous programs, so we won’t go over them all again. However, there are a couple styles that you should know about so that you can customize your version of the game later on.

Find the styles for the container element. These control the size and color of the background. Currently set to green, you can experiment with making this a different color. Also, if you want to make the game wider (and the train travel farther), you’ll need to adjust the width here (as well as in a couple other spots that we’ll show you in a moment).

Now find the styles for the track element. These style the white train tracks. We’ve created the two lines of the tracks by putting a top border and a bottom border on a rectangle that contains the train. If you want to make the train travel farther, this is another spot where you’ll need to make an adjustment (to the width property).

If you’d like, spend a few minutes changing the styles and then clicking Run to see what they do in the Result pane.

remember If you end up doing something that you don’t like or that breaks the look of the game, go to your Public Dashboard and reopen your base version of the program.

Writing the Function Junction JavaScript

Now, move over to the JavaScript pane.

We’ve removed most of the JavaScript from our starting version of the program and replaced it with JavaScript comments telling what needs to be done, as shown in Listing 12-2.

technicalstuff Many of the comments begin with todo:. This is a commonly used way that programmers leave notes to themselves or to other programmers to indicate what needs to be done to finish or to improve their JavaScript code.

Listing 12-2 The JavaScript Pane with Comments Indicating What to Do

/*

todo: Create three global variables:

* trainSpeed (initial value = 250)

* trainPosition (initial value = 0)

* animation (no initial value)

*/

/*

todo: Listen for click events on the train element and call a function named speedUp when they happen.

*/

/*

todo: Listen for click events on the stop button element and call a function called stopTrain when they happen.

*/

function speedUp() {

    /*

    todo: Check whether the train is already going as fast as it can. If not, increase the speed.

    */

    /*

    If the train is already moving, stop it and then restart with the new speed by calling a function called frame.

    */

    function frame() {

        /*

        todo: Reposition the train and check whether the train is crashed.

        */

    }

}

function stopTrain() {

    /*

    todo: Test whether the train is already crashed. If not, stop the train.

    */

}

function checkPosition(currentPosition) {

    /*

    todo: Check the train's current position and crash it if it's at the end of the line.

    */

}

Read through these instructions now. If you’d like, try to complete as many of the items as you can before moving on to our step-by-step instructions.

Now, let’s start at the top and get this train moving!

  1. The first instruction is to create three variables, so underneath this comment, type the following statements:

    var trainSpeed = 250;

    var trainPosition = 0;

    var animation;

  2. The next instruction says to listen for click events on the train. This just means to use the same addEventListener function that we use in earlier chapters to attach a click event handler to the element with an id = "train". Use this code:

    var train = document.getElementById("train");

    train.addEventListener("click", speedUp);

  3. Next, we need to add an event listener to the stop button. The code is similar to the last statement:

    var stopButton = document.getElementById("stopButton");

    stopButton.addEventListener("click", stopTrain);

  4. Now we’re getting to the good stuff. Inside the speedUp() function, the first instruction is to check whether the train is already going at top speed. Here’s the code for that:

    if (trainSpeed > 10) {

            trainSpeed -= 10;

    }

    This code tests the value of the trainSpeed variable. If it’s greater than 10, the train can still go faster, so the next line subtracts 10 from the value of trainSpeed.

    remember The speed of the animation is determined by the second parameter of setInterval, which is how long to wait (in milliseconds) between steps in the animation. So, a smaller number means that there will be less time between steps, which will make the train move faster.

  5. The next thing to do inside the speedUp function is to restart the loop that does the animation, but with the new speed. Type these two lines underneath the previous statement.

       clearInterval(animation);

       animation = setInterval(frame, trainSpeed);

    The first statement, clearInterval, temporarily stops the animation. The second statement starts up a new setInterval loop using the new value trainSpeed. The setInterval function will call a function called frame().

  6. Next, we need to create the frame() function. This function is very similar to the frame() function that we use in Chapter 7 to animate Douglas the JavaScript robot. We just need to make a few adjustments to it for our particular circumstances. Modify the frame() function in your Function Junction program so that it looks like this:

    function frame() {

      trainPosition += 2;

      train.style.left = trainPosition + 'px';

      checkPosition(trainPosition);

    }

    This function first increases the value of the trainPosition variable; then it updates the location of the train according to the current value of trainPosition. After the train has been moved, it makes a call to another function, called checkPosition() and passes it the currentPosition variable.

  7. Next, let’s take a look at the checkPosition() function. Update the checkPosition() function to match the following:

    function checkPosition(currentPosition) {

        if (currentPosition === 260) {

            alert("Crash!");

            console.log("Crash!");

            clearInterval(animation);

        }

    }

    This function accepts a single argument, currentPosition. It tests whether currentPosition is equal to 260 (because 260 pixels is the distance from the left edge of the tracks that we’ve determined to be the point where the train crashes). If you want to make your train tracks longer, this is another spot where you’ll need to change a value.

  8. Finally, move down to the stopTrain() function and make it match the following:

    function stopTrain() {

        if (trainPosition < 260) {

            clearInterval(animation);

        }

    }

    The stopTrain() function runs when the Stop button is clicked. It first tests to make sure that the train hasn’t already crashed, by comparing the trainPosition with the “end of the line” number, which is 260 in this case.

    If you want to increase the length of the tracks, this is the final place where you’ll need to make an adjustment.

  9. Click Update to save your work and then click the train to see if the game works as it should.

    If you did everything right, the train will start to move! If it doesn’t budge, check your work carefully. You can also check in the JavaScript Console to see if there are any error messages that might be helpful with tracking down the problem.

Your turn: Lengthening the tracks!

Throughout this chapter, we told you the places where you need to make changes in order to make the train tracks longer. Now it’s your turn to try it out!

Go through the CSS and the JavaScript and increase the values that need to be increased in order to make the train tracks longer. When you’re finished, click the Update link to try it out! Does your train still crash at the very edge of the background. If not, can you find what you need to change to make it work correctly?

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.224.95.38