0% found this document useful (0 votes)
9 views

Chapter 1 Lesson 3 PDF

Lesson 3 yeah

Uploaded by

mokoneaujan
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views

Chapter 1 Lesson 3 PDF

Lesson 3 yeah

Uploaded by

mokoneaujan
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 16

ICT1512

Chapter 1
Lesson 3

Writing Basic
JavaScript Code
Building Expressions
with Variables
Understanding Events
Structuring JavaScript
Code
Creating a JavaScript
Source File
Objectives

• You will have mastered the material in this lesson


when you can:
– Create and apply JavaScript variables.
– Work with event handlers within a web page.
– Connect to an external JavaScript file.
Using Variables

• Variable: specific location in the computer's


memory where a program stores a value
• First created and assigned a name, then used to
store a value
Assigning Variable Names

• Rules and conventions for variable names, known


as identifiers:
– Must begin with an uppercase or lowercase ASCII letter,
dollar sign, or underscore
– Can include numbers but not as the first character
– Cannot include spaces
– Cannot be a reserved word (a.k.a. keyword)—a
special word that is part of JavaScript syntax
• Best practice is to use camel case, e.g.,
myVariableName
Declaring and initializing variables
• Declaring a variable creates it and thus is mandatory prior to using
the variable
• Initializing a variable assigns it an initial value and is optional
• Syntax for declaring and initializing a variable using the assignment
operator:
let variable = value;
var variable = value;
• Syntax for declaring a variable with a constant (unchangeable) value:
const variable = value;
• Sample statements that declare and/or initialize variables:
let salesTotal; // Declares only
let curOrder = 47.58; // Declares and initializes
salesTotal = curOrder;
let orderNumber = "R0218", salesTotal = 47.58, curOrder;
Building Expressions with Variables
• Expression: a literal value or variable, or a combination of literal
values, variables, operators, and other expressions, that can be
evaluated by a JavaScript interpreter to produce a result
• Expressions are written using:
– Operands: variables and literals (values such as text strings or numbers)
– Operators: symbols used to manipulate operands ( +, -, *, /)
• Example uses of the addition (+) and assignment (=) operators:
let salesTotal = 47.58, shippingCost = 10;
let totalCost = salesTotal + shippingCost;
document.write("<p> Your total costs is $" +
totalCost + "</p>");
Generates the HTML code <p>Your total cost is
$57.58</p>
• Example combine text strings:
5 = “2” return “52” NOT 7
Modifying variables
• Expressions can be used to assign new values to variables at any
point in a script
– Applies to variables declared with let or var; variables declared with const
cannot be modified
– Variables need be declared only once, then can be assigned repeatedly
• Example:
let totalSales = 0;
let item1Sales = 50, item2Sales = 75, item3Sales =
40;
totalSales = item1Sales + item2Sales + item3Sales;
document.write("<p>Total sales = $" + totalSales +
"</p>");

• Writes the HTML <p>Total sales = $165</p> to the web page


Understanding Events
• Event: a specific circumstance (such as an action performed by a
user or an action performed by the browser) that is monitored by
JavaScript and that your script can respond to in some way
– E.g., a user action generates a click event, but a browser triggers a load
event
• Not all events happen with all devices; here are a few examples (part
of Figure 1-14)
Event Keyboard Trigger Mouse Trigger Touchscreen Trigger
change The value of an element,
such as a text box, changes

click A user presses a key when A user clicks an element A user touches an element
an element is selected once and then stops touching it

mouseover A user moves the mouse A user touches an element


pointer over an element

touchend A user removes finger or


stylus from the screen
Working with Elements and Events
• Events are associated with HTML elements, with each element
having its own set of available events
– The click event is available for many elements, including the a element and
form controls created with the input element
– The load and unload events are available for the body element
• Event handler: code that is executed in response to a specific event
occurring on a specific element
• Syntax for an event handler included as an attribute of the initiating
element:
<element onevent="JavaScript code">
• Example using the window.alert() method, which displays the
string passed to it in a dialog box with an OK button:
<input type="submit" onclick="window.alert('Thanks
for your order! We appreciate your business.')" />
Referencing Web Page Elements
• You can reference an element by its id assigned using the
HTML id attribute
• In JavaScript, you look up an element by its id value using
the getElementById() method of the Document object
– Sample HTML creating an input element with the id value
firstName:
<input type="text" id="firstName" />
– Sample JavaScript creating a variable that references that
element:
let fName = document.getElementById("firstName");
– Syntax for changing the value assigned to an attribute thus
retrieved:
document.getElementById("firstName").value =
value; or fName.value = value;
Structuring JavaScript Code
• Including a script element for each code section
– Several script elements can be included in a single HTML file
– Statements in one script section are accessible to subsequent
script sections
• E.g., variables declared in a script section can be used in subsequent script
sections
• Placing the script element
– Place script sections containing the document.write() method
where the content is to be written
– The DOM is created during page load, and a script that references
a part of the page that has not been loaded will cause an error
• Many developers place scripts at the end of the document to avoid this type
of error
• The document.getElementById() method can reference page objects
only after they are loaded into the DOM
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
• 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
Using the async and defer Keywords
(continued)

Figure 1-20
Working with libraries
• Libraries: JavaScript source files that store
especially useful generic scripts used on many
different websites
• You can incorporate a library into HTML code by
creating a script element in the head section and
using the src attribute to specify the file name
• Popular libraries include Node.js, jQuery, and
Modernizr
• Developers usually create customized versions of
large libraries containing only the code they need to
limit download time
Validating Web Pages
• Well formed web page documents conform to the rules and
requirements of HTML
• Validating parser: a program that checks whether a web page is
well formed and whether the document conforms to a specific
language definition known as DTD
– E.g., W3C Markup Validation Service at http://validator.w3.org/
• Validation: the process of verifying that your document is well
formed and checking that the elements in your document are
correctly written according to the element definitions in a specific
DTD
• Embedding JavaScript in an XHTML document
– Enclose the script element within a CDATA section
– Character data (CDATA): a document section that is not interpreted as markup
– Parsed character data (PCDATA): a document section that is interpreted as
markup

You might also like