CHS Web Design Track

JavaScript for Web Warriors, 7eChapter

1: Introduction to JavaScript

Chapter Objectives

By the end of this chapter, you should be able to:

  • Explain the history of JavaScript and scripting languages and how each has been developed for its current use.
  • Write content into a web page using JavaScript.
  • Add JavaScript code to a web page.
  • Create and apply JavaScript variables.
  • Work with event handlers within a web page.
  • Connect to an external JavaScript file.

Exploring the JavaScript Language

Introducing scripting languages

  • JavaScript is a type of programming language, specifically a scripting language
  • Programming language: a set of instructions directing the actions of the computer
    • Typically must be compiled into machine code by a program called a compiler
  • Scripting languages subcategory of programming languages that run directly from a program or script (are not compiled)
    • Must be interpreted (read and scanned line-by-line) by an interpreter
  • Markup languages languages that define the content, structure, and appearance of a document
    • HTML (Hypertext Markup Language) defines the content and structure of a web page
    • CSS (Cascading Style Sheets) defines how a web page will appear on a specified device
The roles of HTML, CSS, and JavaScript in web development

JavaScript and ECMAScript

ECMAScript EditionDate IssuedFeatures
6th Edition (ES6) June 2015Added new syntax for complex applications, included iterators and for . . . of loops, arrow functions, variable declarations using let and const
7th Edition (ES7) June 2016Added block-scoping of variables, exponentiation operator, and support for asynchronous execution
8th Edition (ES8) June 2017Added support for async/await constructions
9th Edition (ES9) June 2018Included rest/spread operators for variables, asynchronous iteration, and additions to regular expressions
10th Edition (ES10)June 2019Added features to object prototypes and changes to Array sorting
11th Edition (ES11)June 2020Added an optional object chaining operator for array and functions

The DOM and the BOM

DOM Date Features
DOM Level 01995 Provided a basic interface to access the contents of a web page using the initial version of JavaScript
DOM Level 1October 1998 Added a way of mapping the content of a web page to JavaScript keywords, functions, properties, and methods
DOM Level 2December 2000 Added an interface to events occurring within the web page, the contents of CSS style sheets, and the ability to transverse and manipulate the hierarchical structure of the web page content
DOM Level 3April 2004 Added support for methods to load and save web documents, validate web forms, and provides the ability to work with keyboard objects and events
DOM Level 4November 2015 An ongoing “living standard” that is updated to reflect the events and actions occurring within the document model based on the evolving needs of the market and mobile devices

Understanding client/server architecture

  • Traditionally, a two-tier system consisting of:
    • Server (back end): a device or application from which a client requests information; responsible for data storage, management, communication with external services, and heavy processing
    • Client (front end): a device or application that presents an interface to the user and requests information from a server; responsible for gathering information from the user, submitting it to a server, then receiving, formatting, and presenting the results, and sometimes some related data processing
  • Web's two-tier client/server system consists of a web browser and web server that communicate via Hypertext Transfer Protocol (HTTP)
  • Adding databases and other applications to a web server yields a three-tier client/server system (a.k.a. multitier client/server system, n-tier client/server system): client tier, processing tier (a.k.a. middle tier), and data storage tier
A two-tier client/server system
A three-tier client/server system

JavaScript and client-side scripting

Understanding server-side scripting

  • Server-side scripting: programming using a scripting language (e.g., PHP, ASP.NET, Python, Ruby) that is executed from a web server
  • These languages work in the processing tier and can handle communication between the client and data storage tiers, often preparing and processing data
  • JavaScript and server-side scripts operate in separate environments but must work together to deliver interactive websites to users
How a web server processes a server-side script

Should you use client-side or server-side scripting?

Class Discussion

How does the Internet affect your daily life? Try to imagine and describe how it would be different if the Internet ceased to be available to you.

Quick Check
  1. In the web's two-tier client/server system, the client is an application called a(n) _____. (1.1)
  2. True or False: HTML and CSS are common web page scripting languages that are interpreted as they are run. (1.1)
  3. The architecture of the web evolves into a _____ client architecture once you start adding databases and other types of applications to a web server. (1.1)
  4. Writing programs that prepare and process data and handle communication between the client and data storage tiers for a web application using a language such as PHP is known as _____. (1.1)
  5. True or False: JavaScript is a client-side scripting language that allows web page authors to develop interactive web pages and sites. (1.1)
  6. The three foundations upon which the full implementation of JavaScript is built are ECMAScript, the _____, and the Browser Object Model. (1.1)
  7. A set of procedures that access an application such as a web page or a web browser, such as the Browser Object Model, is known as a(n) _____. (1.1)

Writing a JavaScript Program

IDEs and code editors

  • Use an Integrated Development Environment (IDE) to manage all of the facets of website development
  • Use a code editor to manage coding in HTML, CSS, and JavaScript within a graphical interface
Figure 1-7 Completed Tinley Xeriscapes Plants page using JavaScript
U.S. Department of Agriculture
To open the Tinley Xeriscapes page:
  1. Use your code editor to go to the js01 < chapter folder of your data files.
  2. Open the js01_txt.html file in your code editor.
  3. Within the head section of the HTML file, enter your name and the date in the Author and Date lines.
  4. Save the file as js01.html.

The script element

To add the script element to the page:
  1. Scroll down to the article element in the js01.html file within your code editor.
  2. After the opening <figcaption> tag, type:
    <script>
    </script>
    indenting the opening and closing tags to make your code easier to read. See Figure 1-8.
  3. Save your changes to the file.
Adding a script element

Understanding JavaScript objects

Using the write() method

To apply the document.write() method:
  1. Return to the js01.html file in your code editor.
  2. Between the opening and closing <script> tags, add the following statements as shown in Figure 1-9:
    document.write("<p>Plant choices for ");
    document.write("<a href='http://planthardiness.ars.usda.gov'>");
    document.write("hardiness zones</a>");
    document.write(" 5a - 6b </p>");
  3. Save your changes to the file and then refresh or reload the s01.html file in your web browser. As shown in Figure 1-10, the page should now display the content created by the four document.write() statements.
  4. Click the hardiness zones link from the inserted content and verify that your browser loads a Plant Hardiness Zone map.
  5. Return to the js01.html file in your browser.
Applying the document.write() method
Content generated using the document.write() method

Case sensitivity in JavaScript

Adding comments to a JavaScript program

To add JavaScript comments to the js01.html file:
  1. Return to the js01.html file in your code editor.
  2. Add the following block comment directly after the opening <script> tag:
    /*
    Information on available plants
    including link to USDA website
    */
  3. Position the insertion pointer after the semicolon at the end of the last statement containing the document.write() method, and type the following line comment:
    // hardiness zones for Chicago and surrounding area
    See Figure 1-11.
  4. Save your changes to the file and then reopen js01.html in your web browser. Verify that the JavaScript comments are not displayed in the browser and that the content generated by the document.write() statements has not changed.
Adding JavaScript comments
Quick Check
  1. A JavaScript program is composed of _____ that are contained within the script element and that, by convention, end in semicolons. (1.3)
  2. JavaScript is object based, which means that JavaScript programmers use and create objects with associated data, called properties, and associated procedures, called _____.
  3. Often, you must pass one or more pieces of information, called _____, to a procedure associated with an object so that it will be executed as desired. (1.3) Answer: arguments
  4. Good JavaScript programmers typically add helpful notes to their source code documents by inserting _____, lines of code that are not processed by browsers. (1.3)

Writing Basic JavaScript Code

Using variables

Assigning variable names

abstract char double finally in null super try
arguments class else float instanceof package switch typeof
await const enum for int private synchronized var
boolean continue eval function interface protected this void
break debugger export goto let public throw volatile
byte default extends if long return throws while
case delete FALSE implements native short transient with
catch do final import new static TRUE yield

Declaring and initializing variables

To declare variables for three plant images:
  1. Return to the js01.html file in your code editor.
  2. Directly before the closing </script> tag, press Enter and type the following JavaScript statements containing the file names of three plant images:
    //define variables containing plant file names
    let blanket = "blanket.jpg";
    let bluestem = "bluestem.jpg";
    let rugosa = "rugosa.jpg";
    See Figure 1-13.
  3. Save your changes to the file.
Declaring JavaScript variables
Quick Quiz
  1. The values a program stores in computer memory are commonly called _____. (1.4)
  2. The name you assign to a variable is called a(n) _____. (1.4)
  3. Special words that are part of the JavaScript language syntax are called ____. (1.4)
  4. True or False: Identifiers must begin with an ASCII letter. (1.4)
  5. True or False: The plus sign (+) is called the assignment operator. (1.4)
  6. True or False: JavaScript is case sensitive. (1.4)

Building Expressions with Variables

Building an expression

Modifying variables

Knowledge Check
  1. Imagine a colleague writes some JavaScript code containing a companionAnimal object. What is an object? What do the following statements from this program do?
    companionAnimal.fillFoodBowl(“treats”);companionAnimal.name = “Marco”
  2. Describe what each of the following JavaScript statements is and what it does.
    const accelerationDueToGravity = 9.81;
    let ballMass = 3, dropHeight;
    dropHeight = landElevation + structureHeight;
    document.write(“<p>A “ + ballMass “ kg ball fell “ dropHeight “ m.</p>”);

Understanding Events

Event Keyboard TriggerMouse TriggerTouchscreen Trigger
blur An element, such as a radio button, becomes inactive
changeThe value of an element, such as a text box, changes
clickA user presses a key when an element is selectedA user clicks an element onceA user touches an element and then stops touching it
errorAn error occurs when a document or image is being loaded
focusAn element, such as a command button, becomes active
keydownA user presses a key
keyupA user releases a key
loadA document or image loads
mouseoutA user moves the mouse pointer off an elementA user stops touching an element
mouseoverA user moves the mouse pointer over an elementA user touches an element
resetA form’s fields are reset to its default values
select
touchendA user selects text
submitA user submits a form
touchendA user removes finger or stylus from the screen
touchmoveA finger or stylus already touching the screen moves on the screen
touchstartA user touches a finger or stylus to the screen
unloadA document unloads

Working with elements and events

Referencing web page elements

To add event handlers to the plants.htm file:
  1. Return to the js01.html file in your code editor.
  2. Within the aside element, in the opening tag for the first li element, add the following event handler:
    onclick="document.getElementById('plantImg').src = blanket"
  3. In the opening tag for the second li element, add the following event handler:
    onclick="document.getElementById('plantImg').src = rugosa"
  4. In the opening tag for the third li element, add the following event handler:
    onclick="document.getElementById('plantImg').src = bluestem"
    Figure 1-17 shows the revised code in the file.
  5. Save the file, refresh or reload it in your web browser, and then click each plant name on the left side of the page. The picture of each flower should be displayed in the main section of the web page when you click its name. If the page doesn’t load, or if you receive error messages, make sure that you typed all the JavaScript code in the correct case. (Remember that JavaScript is case sensitive.) Figure 1-18 shows the web page after clicking Hedge Rose.
Changing the source of an inline image using JavaScript
Web page after clicking Hedge Rose
U.S. Department of Agriculture
Quick Quiz
  1. JavaScript code that is executed in response to a specific event for a specific web page element is a(n) _____. (1.5)
  2. The Document Object Model allows you to reference any element on a web page using the value assigned to its HTML _____ attribute.
Discussion Question

What JavaScript characteristics do you consider most and least helpful to you as a programmer based on what you have learned so far? Explain why. (1.3, 1.4, 1.5)

Structuring JavaScript Code

Quick Check
  1. True or False: Statements in one script section of an HTML file are accessible to all subsequent script sections. (1.3)
  2. True or False: Because multiple scripts placed within an HTML file can access one another, they can be positioned anywhere in the file without a risk for errors during page loading. (1.3)

Creating a JavaScript Source File

  • A JavaScript source file contains only JavaScript code and has a .js extension
  • Referencing an external file
    • Syntax for attaching a web page to a JavaScript source file from within the HTML file:
      <script src=”url”></script>
      where url is the JavaScript source file's name and location
    • The script element can be used for embedding JavaScript code or referencing a file—not both at once
  • Using the async and defer keywords (script element attributes)
    • Default behavior is for commands in an external .js file to be loaded when the browser initially encounters the script element in the HTML file
    • With the async attribute, the browser parses the HTML and JavaScript code together, only pausing to process the script
    • With the defer attribute, the browser parses and loads the HTML, then processes the script
    • Placing JavaScript code in an external file is preferable because:
      • Code can be shared among pages or among team members
      • When shared among pages, code need only be downloaded once
      • The HTML file is kept neater and cleaner
      • Websites are easier to manage when the HTML, CSS, and JavaScript files each focus on one task
Loading HTML and JavaScript code
To connect to an external JavaScript file:
  1. Open the js01_txt.html file in your code editor. Enter your name and the date in the head section of the file.
  2. Directly above the closing </head> tag insert the following <script> tag to connect the page to the js01b.jsfile as shown in Figure 1-22.
    <script src="js01b.js" defer></script>
  3. Save the file as js01b.html and close your code editor.
  4. Open js01b.html in your web browser.
  5. Verify that the hyperlink for hardiness zones appears on the page and that clicking the hardiness zones links opens the appropriate page.
  6. Return to the js01b.html file in your browser and verify that clicking the list of plants on the left margin displays the corresponding plant time.
Connecting to an external JavaScript file

Working with libraries

Quick Quiz
  1. True or False: To access JavaScript code that is saved in an external file, a programmer uses the js attribute of the <script> element. (1.6)
  2. To tell the browser to parse the HTML and JavaScript code for a page together, add the _____ attribute to the opening <script> tag referencing an external .js file. (1.6)

Validating Web Pages

Activity 1.2: Think, Pair, and Share
  1. Form pairs/groups of two to three class members.
  2. Your group will attempt to modify the Tinley Xeriscapes “Plants” web page from Chapter 1 so that an additional plant is added to the left-side menu. Open the completed HTML and JavaScript files for this project in a code editor. Together, examine the code and make a list of the changes you will need to make to add another plant option that users can click on to see an additional photo image.
  3. Choose a plant to add to the menu. Make the necessary modifications that you identified to the HTML and JavaScript code.
  4. Optionally, locate a JPEG file of your chosen plant and add it to the appropriate folder so that you can see the new image when you click on the plant in the menu. Be sure to incorporate the file name in the code where it belongs.
Activity 1.3: Discussion Questions
  1. How does the Internet affect your daily life? Try to imagine and describe how it would be different if the Internet ceased to be available to you.
  2. What JavaScript characteristics do you consider most and least helpful to you as a programmer based on what you have learned so far? Explain why.
Self-Assessment
  1. Are you interested in professional server-side web development? Why or why not? If so, how do you expect the experience you are gaining with JavaScript to be helpful to you as a server-side developer?
  2. Which IDEs and/or code editors have you used or considered using? What do you like and dislike about the tools you are currently using for website development?
  3. How would you describe the value of using JavaScript to develop web applications used by business organizations to attract and serve customers? What value would you say it offers for web applications with other purposes?