HTMLCourse Basic/Notes/Week4

From MozillaWiki
Jump to: navigation, search

Javascript

Download the files for this class here: <a href="http://robynoverstreet.com/mozilla/week4/files">http://robynoverstreet.com/mozilla/week4/files</a>

Javascript is a programming language for the web. Technically, it's what's called a scripting language, which means it's a somewhat simplified programming language.

Javascript is a client-side scripting language, which means that the code gets executed in the user's browser, and not on the web server. Because Javascript works in the browser, it requires that users have javascript turned on in their browser settings. Javascript is almost always on by default, but a user can turn it off if he or she chooses. Just something to keep in mind. Just like with HTML, you can't be 100% sure that the user will see what you expect. But you can be reasonably sure.

Javascript operates within HTML. It adds action, or behavior, to a web page. It can change HTML after it is loaded to the browser, without reloading the page. For example, it can change one image to another image when a user clicks a button or hovers over an element.

Your First Javascript

We can put javascript inside an HTML document using the <script> tag. Once we start working with more involved javascript, we'll separate out our script into a separate file and link it in (very similar to what we do with CSS) but for now, we'll work inside the script tag.

In the browser

Javascript has the ability to write HTML into a page after its been loaded. That's what we're going to do with the document.write() command. The following code goes inside the <head> tag in html.

<script>
    document.write('Hello world');
</script>

A lot of javascript code looks similar to this -- it has an element and an action. "document" is the element -- it refers to the entire HTML document -- and "write()" is the action, more commonly called a "method" in programming. Inside the parentheses of the write method, you put the text you want to write to the document.

In Firebug

Using the Firebug plug-in for Firefox, we can also output information from Javascript using the console.log() command. This is a great way of testing and debugging when we don't want to display everything on the page itself.

<script>
    console.log('Hello console');
</script>

Similar to document.write(), with console.log(), "console" is the element (also called an "object") and "log" is the method.

Exercise

Write out to the browser and then write out the console.

Programming Basics: Variables

The most essential elements of any programming language are variables. Variables are the storage units in programming. You can set a variable to store a piece of information and then use that piece of information throughout your script. For example, let's say you created a web site that your users can log in to. At the top of each page, you want to greet your user by name. It would be way too much work to create a new page for each user. You'd simply set a variable to store the user's name. That way, you can change the value of the variable instead of changing the whole page. For example:

<script>
    var username;
    username = 'Bob';
    document.write('Hi '+ username);
</script>

In Javascript code, we use the term var to refer to a variable. The word after var is the name of our variable. In this case, the variable is called username. You can name a variable (almost) anything you want. It has to start with a letter, and can only contain letters, numbers, and underscores. Variables are case-sensitive. So the variable myName is not the same as the variable myname.

On the following line, we give the variable a value. We're setting the username to 'Bob' here. Variables that are text need to be in quotes. Numbers do not need quotes. A piece of text in JavaScript (and in any programming language) is called a string.

In the third line, we output the greeting. We use the string 'Hi ' and the variable username (the variable name doesn't need quotes).

   To join these two values together, we use the plus sign (+). 
   Joining strings together is called concatenation.</p>

Notice also that every line in Javascript ends in a semicolon.

Numbers. Numbers in javascript are even easier than strings. They don't require quotation marks, since they're not text. And you can add, subtract, multiply or divide them (plus a lot of other mathematical functions).

<script>

    var favorite_number = 6;

    var number_plus_one = favorite_number + 1;

    var one_less = favorite_number - 1;

    var double_number = favorite_number * 2;

    var half_number = favorite_number / 2;

    </script>

Accessing parts of the DOM

<p>Using document.write() is a kind of crude way of updating the HTML page, as it doesn't offer much control over where the new content is placed. Usually, you'll want to update a very specific part of the page. Javascript allows you to find parts of the HTML (aka, the DOM) by identifying parts like tag name or id.

<script>
    document.getElementById('sidebar');
</script>

The method getElementById offers a handy way to access one element with a particular id attribute. Once you can access it, you can manipulate it. For example, we can change the content of the element:

<script>
    var infobox = document.getElementById('info');
	  infobox.innerHTML = "My new content";
</script>

Using the innerHTML property, you can replace all the content inside the element with the HTML that you choose.

Exercise

Change the content of a div using innerHTML.

Listening to the user

Often you'll want to change the DOM when the user does something and not right away. That's where event listeners come in. With the "onclick" event listener, for example, you can add javascript right in the tag to happen when the user clicks that element.

<div id="clicker" onclick="document.getElementById('info').innerHTML='You clicked';">Click me</div>

Notice that "onclick" is an attribute of the tag, just like "id", "style" or any other attribute.

Changing the CSS when a user clicks. In addition to changing the content, you can also change the CSS styles of an element with Javascript. For example, we can change the background color of an element when a user clicks.

<div id="clicker" onclick="document.getElementById('info').style.backgroundColor = '#333';">Click me</div>

Notice how the syntax changes slightly between CSS and Javascript. In CSS, the property is "background-color", while in Javascript, it's "backgroundColor". Try changing other CSS properties -- a fun one to try is the display property, making elements appear and disappear.

Other event listeners to know:

  • onmouseover and onmouseout (for rollovers)
  • onload

Exercise

Make something happen when the user does something. Use an event listener like onclick or onmouseover

Programming Basics: Functions

Sometimes you'll want several things to happen on a single action, and it becomes cumbersome to put all of those instructions inside one tag. That's where functions come in handy. Functions are sets of programming instructions that can be called all at once. They become very useful in conjunction with event handlers.

Here's an example of a function called "changeBox" that changes both the content and the background color of an element with the id of "info":

<script>
    function changeBox(){
		 var infobox = document.getElementById('info');
	  	 infobox.innerHTML = "My new content";
		 infobox.style.backgroundColor = '#333';
	  }
</script>

Now when we use the onclick handler, we only have to use the name of the function:

<div id="clicker" onclick="changeBox();">Click me</div>

Programming Basics: Arrays

Arrays are variables that hold multiple pieces of data. So far, we've been working with variables that hold just one piece each, as in:

    var username = "Bob";
    var food = "Spaghetti and meatballs";
    var age = 25;
    

With arrays, we can store a list of information. For example:

    var people = new Array("Bob","Maria","Jennifer","Tony");
    

In Javascript, to create a new array, you have to make a new array object, as above. We just call the new array by writing new Array(). If we want to put items in the array when we create it, we can put the items inside the parentheses. Each item is separated by a comma. You can use numbers or strings or both in an array.

To add an item to the end of an array, we can use the Array.push() function. Like this:

    var stuff = new Array('shoe','car','apple');
    stuff.push('baseball');
    

Index numbers in Arrays. To keep track of items in an array, each array automatically assigns a number to the items. Unlike in the real world, in the programming world, counting starts with zero. So in the array above, the item 'shoe' has the index number 0, 'car' is number 1, and so on.

To select an item in an array by index number, we use the name of the array and square brackets, like this:

    var thing1 = stuff[0];
    var thing3 = stuff[2];
    

We can also set items in array using the same syntax. For example, if we wanted to replace the value 'apple' with 'orange' we'd do it this way

    stuff[2] = 'orange';
    

An Array of Tags

Using the method getElementById, we are generally looking for one single element. There are also methods that can fetch multiple elements, such as all elements of a certain tag:

	document.getElementsByTagName('p');

The above code gets all the paragraph tags (<p>) within an HTML document. It returns the results as an array. To do the same thing to each item in the array, we can use a loop.

Exercise

Print out an array of paragraph elements to the console using the console.log() method.

Looping Through an Array

One of the reasons to use arrays in programming is so we can store pieces of information we want to treat in the same ways. For example, if we have an array of items available for purchase, we might want to list out all the items on a page. Or if we have an array of prices, we might want to add a shipping charge to each price.

To process each item in an array, we use a loop. With a loop, we can go through the array and perform the same actions on the each item in the array.

The most common loop in Javascript is a for loop. It looks like this:

    for (i=0;i < stuff.length; i++){
    	document.write(stuff[i]);
    }	
    

Inside the parentheses of a for loop, there are 3 statements, each separated by a semicolon(;).

i=0 The first statement sets up a variable that will be used throughout the loop, and will change each time through the loop. You can call this variable anything you want, but the convention is to call it i. In the example above, the first statement sets the variable, i, to zero. That's the starting number for the loop. The first time through the loop i will be equal to 0.

i++. Let's skip to the third statement for a minute, because it's an easy one. This sets how the variable i will change each time through the array. i++ is just a shorthand for saying i+1. So each time through the loop, the variable i will be equal to one more than it equalled the last time through the loop. In the example above, i starts with 0. Then the second time through the loop, it will be 1; the third time it will be 2, and so on.

i < stuff.length. The second statement tells the loop when to stop looping. (If there's nothing to stop the loop, it will go on forever. Computer programs are dumb that way.) So, this statement is saying, keep looping until i is less than the the number of items in that array called stuff. All arrays have a length property that will give you the number of items contained within the array. You can access the length of any array with the syntax nameOfArray.length (where nameOfArray is actually the name of your array, of course).

stuff[i]. Inside the loop, instead of writing the index number directly, like stuff[2], let the variable i stand in for the index number. That way, the first time through the loop, stuff[i] will stand for stuff[0], the second time stuff[i] will stand for stuff[1], and so on.

That way, we don't have to know how many things are in an array, we just do the same thing to each item in the array. (In the example above, the only thing we do is write the item out to the browser.)</p>

The really great thing is that instead of writing the same commands over and over again, we just write it once and let the loop do the work.

Exercise

Loop through the list of paragraph elements and change the background color on each.

jQuery

jQuery is a library for javascript designed to make common tasks in javascript much easier. If you're wondering what a "library" is, it's just a set of functions that you can bring into your code and use.

The first shortcut to know involves selecting elements. jQuery uses the dollar sign character ($) as a function to let you select a variety of DOM elements. In regular Javascript, to get a div element with an id of "box", you'd need to type:

document.getElementById('box');

whereas in jQuery, you only need:

$('#box');

Notice the pound sign (#) used for id, just like in CSS. You can also use a period to indicate a class, like in CSS.

$('.special');

To use jQuery in your code, you need to put a link to the script in your HTML head tag, like so:

<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js"></script>
<head>

Visual Effects in jQuery

Now for the fun stuff. jQuery has a bunch of built-in functions to create visual effects in javascript. You can fade elements in and out, show and hide them, or slide them in or out, for example. Take a look at the options here: <a href="http://api.jquery.com/category/effects/">http://api.jquery.com/category/effects/</a>

Here's an example of sliding a div out of the display in an upwards direction:

$('#mybox').slideUp();

For more information on this particular function, see <a href="http://api.jquery.com/slideUp/">http://api.jquery.com/slideUp/</a>

Exercise

Use jQuery to target an element and change it with an effect.