Web Design & Application Development

Phoenix, AZ • 480-788-4635

Web Development

Lesson 4: JavaScript

1. Intro to JavaScript

HTML and CSS are mostly static, but JavaScript can allow us to make changes to our website in response to user input like the example below:

Example 1

Click the button below to see JavaScript in action!

Here is the code used to create the button and its surrounding container:

Example 1 HTML

                              
                                <div class="questions_container"  id="example1container">
                                    <h2>Example 1</h2>
                                        <div>Click below to see JavaScript in action!</div>
                                            <div class="quiz_lesson_container">
                                        <button type="button" id="exampleButton1"> Click Me!</button>
                                    </div>
                                </div>
                              
                            

JavaScript gives us access to our entire HTML file in its document object. It uses the HTML tags we defined to break down our HTML. The document object model, or DOM, can be visualized something like this:

Lesson 4 Slide
Figure - The DOM

Everything we've done so far (adding and removing tags in HTML, changing the content of tags, and adding and removing CSS styles from tags) can also be done with JavaScript.

Below is the JavaScript code for the example above (with some comments):

Example 1 JavaScript

                              
                                // First, we create a variable to reference the button.
                                // Which button? The one with the id attribute of 'exampleButton1'
                                var exampBtn1 = document.getElementById('exampleButton1');

                                // If we have a reference to our button in a variable,
                                // JavaScript gives us the .onclick event which calls a
                                // function when the button is clicked.
                                // A function is a way of telling JavaScript: Do Something!
                                // When our button is clicked, JavaScript will do everything
                                // inside the brackets below.

                                exampleButton1.onclick = function() {
                                    var example1cont = document.getElementById('example1container');
                                    example1cont.style.background="#ffeb38";
                                    example1cont.style.border="2px solid #B80000";
                                    exampBtn1.innerHTML = "Thanks!"
                                }

                                // Inside this function, we create another variable: exampInput1 to
                                // reference the input we'll be changing.
                                // JavaScript lets us set the .style property to change or add a
                                // CSS declaration.
                                // Using the .innerHTML property, we can also change the text on
                                // the button.  This property replaces the "stuff" inside the
                                // particular tag.
                                
                            

JavaScript is well-known for its ability to alter websites in response to user actions, but it's actually a much more powerful programming language than many people realize.

To get started, we need to know a little bit about the basics.

2. Variables

First off, JavaScript Variables are containers for storing data values. These variables can change as our program runs and in response to the user's actions. We should declare a variable by using the var keyword before it.

Variables

                              
                                  var price1 = 5;  //The values for these variables could be user-entered.
                                  var price2 = 6;
                                  var total = price1 + price2; // total returns 11

                                  var firstName = "Jane" // variables can refer to text also known as "Strings"
                                
                            

3. Arithmetic Operators

We can use the following operators to perform arithmetic

Operator Description
+ Addition
- Subtraction
* Multiplication
/ Division
% Modulus
++ Increment
-- Decrement

Arithmetic Operators

                          
                            //ADDITION
                            var a = 10;
                            var b = 20;
                            var c = a + b ; // c returns 30;

                            //SUBTRACTION
                            var a = 10;
                            var b = 20;
                            var c = a - b ; // c returns -10;

                            //MULTIPLICATION
                            var a = 10;
                            var b = 20;
                            var c = a * b ; // c returns 200;

                            //DIVISION
                            var a = 10;
                            var b = 20;
                            var c = b / a ; // c returns 2;

                            //MODULUS (Remainder from division)
                            var a = 10;
                            var b = 20;
                            var c = b % a ; // c returns 0;

                            var x = 2;
                            var y = 9;
                            var z = y % x ; // z returns 1;

                            //INCREMENT
                            var a = 10;
                            a++ ; // returns 11;

                            //DECREMENT
                            var a = 10;
                            a-- ; // returns 9;
                          
                        

Q. What are some uses of the ++ operator?

  • A. Incrementing the score in a game.
  • A. Counting

Q. What are some uses for the % operator?

  • A. Calculating if a number is even or odd.
  • A. Clock Arithmetic

4. Assignment Operators

Assignment Operators assign values to variables. We'll just need to know about the = operator, but there are others.

Operator Example Same As
= x = y x = y
+= x += y x = x + y
-= x -= y x = x - y
*= x *= y x = x * y
/= x /= y x = x / y
%= x %= y x = x % y

5. Comparison Operators

We use Comparison Operators to compare two or more values.

Note that to test "equals to" we use == or two equals signs, not one.

Operator Description
== equal to
=== equal value and equal type
!= not equal
!== not equal value or not equal type
> greater than
< less than
>= greater than or equal to
<= less than or equal to
? ternary operator

6. Functions

A function is a JavaScript procedure — a set of statements that performs a task or calculates a value

                        
                        /**

                         A function definition (also called a function declaration, or function
                         statement) consists of the function keyword, followed by:

                          The name of the function.

                          A list of arguments to the function, enclosed in parentheses and
                          separated by commas.

                          The JavaScript statements that define the function, enclosed in
                          curly brackets, { }.

                        **/

                          function square(number) {
                            return number * number;
                          }

                          var square = function(number) { return number * number };
                          var x = square(4) // x gets the value 16
                        
                      

Now, for a challenge.

CHALLENGE: Create a function that takes a number of minutes and prints out both hours and minutes.

For example, given the number 89, the function would print out:

                          

                            // "Hours: 1"
                            // "Minutes: 29"
                          
                        

Here's an HTML file with a <script> tag for your JavaScript:

File: jstester.html

                            
                              <!DOCTYPE html>
                              <html>
                                <head>
                                  <title>JavaScript Tester</title>
                                </head>
                                <body>
                                  <h1>My JavaScript Tester</h1>
                                  <script>
                                  // Your JavaScript Goes Here


                                  </script>
                                </body>
                              </html>
                            
                          
Figure - Starting HTML

Here are some steps and hints to help you:

  1. Declare a function - use the var keyword and give your function a name. Remember to allow your function to accept a parameter - this will be where we will pass the function the number of minutes.
  2. Inside the function, declare two variables named: hours and minutes.
  3. Also inside the function, add the lines below. This will print your answer to the console.
  4. Write out how you want to solve the problem in plain language first, then use the tools JavaScript gives you to execute your plan.
                          

                              console.log("Hours: " + hours);
                              console.log("Minutes: " + minutes);

                          
                        

HINT: Use the modulus operator.

HINT: Use a method from JavaScript's built-in Math object.

                          
                            /** Test out each of the following number of minutes to make sure the function works:

                            45
                            "Hours: 0"
                            "Minutes: 45"

                            119
                            "Hours: 1"
                            "Minutes: 59"

                            800
                            "Hours: 13"
                            "Minutes: 20"


                            **/
                          
                        

7. Objects

We've seen how variables can refer to text, numbers, HTML tags. They can also refer to what are known as objects - groups of name / value pairs that refer to a particular thing.

Defining Objects

                          
                            var car = {type:"Fiat", model:"500", color:"white", mpg:50};
                            var person = {firstName:"John", lastName:"Doe", age:50, eyeColor:"blue"};
                          
                        

The values are written as name:value pairs (name and value separated by a colon).

In the name:value pairs, the "name" (first thing) is known as a property of the object.

Object Methods

                          
                            var person = {
                                firstName:"John",
                                lastName:"Doe",
                                age:50,
                                eyeColor:"blue",
                                fullName: function() {
                                            return this.firstName + " " + this.lastName;
                                            }
                            };
                          
                        

Accessing Object Properties & Methods

                          
                            var person = {
                                firstName:"John",
                                lastName:"Doe",
                                age:50,
                                eyeColor:"blue",
                                fullName: function() {
                                            return this.firstName + " " + this.lastName;
                                            }
                            };

                            // We can access object properties two ways:
                            // objectName.propertyName
                            // objectName["propertyName"]

                            person.lastName    // equals "Doe"
                            person["lastName"] // also equals "Doe"

                            // And we can access methods like so:
                            // objectName.methodName()

                            name = person.fullName();   // equals "John Doe"
                          
                        

8. Arrays

JavaScript arrays are used to store multiple values in a single variable.

We can have arrays made up of various things: Strings, numbers, boolean values, or even entire objects

Creating Arrays

                          
                            var cars = ["Saab", "Volvo", "BMW"];

                            // is the same as:

                            var cars = [
                                "Saab",
                                "Volvo",
                                "BMW"
                            ];
                          
                        

Array elements are refered to by their index number. Array indexes start with 0, not 1 and are put in brackets after the variable name

Accessing Array Elements

                          
                            var cars = ["Saab", "Volvo", "BMW"];

                            cars[1] = "Volvo"