JavaScript
Introduction
JavaScript Can Change HTML Content
One of many JavaScript HTML methods is getElementById().
This example uses the method to "find" an HTML element (with id="demo") and changes the
element content (innerHTML) to "Hello JavaScript":
Example
[Link]("demo").innerHTML = "Hello JavaScript";
JavaScript Can Change HTML Content
One of many JavaScript HTML methods is getElementById().
This example uses the method to "find" an HTML element (with id="demo") and changes the
element content (innerHTML) to "Hello JavaScript":
Example
[Link]("demo").innerHTML = "Hello JavaScript";
What is JavaScript?
▻ It is designed to add interactivity to HTML pages
▻ It is a scripting language (a lightweight programming language)
▻ It is an interpreted language (it executes without preliminary compilation)
▻ Usually embedded directly into HTML pages
▻ And, Java and JavaScript are different
▻ JavaScript gives HTML designers a programming tool:
▻ simple syntax
▻ JavaScript can put dynamic text into an HTML page
▻ JavaScript can react to events
▻ JavaScript can read and write HTML elements
▻ JavaScript can be used to validate data
▻ JavaScript can be used to detect the visitor’s browser
▻ JavaScript can be used to create cookies
▻ Store and retrieve information on the visitor’s computer
JavaScript How To
The HTML <script> tag is used to insert a JavaScript into an HTML page
<script type=“text/javascript”>[Link](“Hello World!”)</script>
Ending statements with a semicolon?
Optional; required when you want to put multiple statements on a single line
JavaScript can be inserted within the head, the body, or use external JavaScript file
How to handle older browsers?
<script type=“text/javascript”>
<!—
[Link](“Hello World!”)
// -->
</script>
JavaScript Basics
Variables
variables are declared with the var keyword (case sensitive)
types are not specified, but JS does have types ("loosely typed")
Number, Boolean, String, Array, Object, Function, Null, Undefined
can find out a variable's type by calling typeof
Syntax:
var name = expression;
Example
var clientName = "Connie Client";
var age = 32;
var weight = 127.4
If … Else
Use if to specify a code block to be executed, if a specified condition is true
Use else to specify a code block to be executed, if the same condition is false
JavaScript allows almost anything as a condition
Syntax
if (condition) {
statements;
} else if (condition) {
statements;
} else {
statements;
Switch
Based on a condition, switch selects one or more code blocks to be executed.
switch executes the code blocks that matches an expression.
switch is often used as a more readable alternative to many if...else if...else statements,
especially when dealing with multiple possible values.
Syntax
switch(expression) {
case x:
// code block
break;
case y:
// code block
break;
default:
// code block
}
This is how it works:
The switch expression is evaluated once.
The value of the expression is compared with the values of each case.
If there is a match, the associated block of code is executed.
If there is no match, no code is executed.
Operators
Logical operators
< >= <= && || ! == != === !==
most logical operators automatically convert types:
5 < "7" is true
42 == 42.0 is true
"5.0" == 5 is true
=== and !== are strict equality tests; checks both type and value
"5.0" === 5 is false
Boolean type
any value can be used as a Boolean
o "falsey" values: 0, 0.0, NaN, "", null, and undefined
o "truthy" values: anything else
converting a value into a Boolean explicitly:
o var boolValue = Boolean(otherValue);
o var boolValue = !!(otherValue);
Example:
var iLike190M = true;
var ieIsGood = "IE6" > 0; // false
if ("web devevelopment is great") { /* true */ }
if (0) { /* false */ }
Popup Boxes
alert("message"); // message
confirm("message"); // returns true or false
prompt("message"); // returns user input string
Alert Box:
An alert box is often used if you want to make sure
information comes through to the user.
When an alert box pops up, the user will have to click
"OK" to proceed.
Syntax
[Link]("sometext");
Confirm Box:
A confirm box is often used if you want the user to verify or
accept something.
When a confirm box pops up, the
user will have to click either "OK"
or "Cancel" to proceed.
If the user clicks "OK", the box
returns true. If the user clicks
"Cancel", the box returns false.
Syntax
[Link]("sometext");
Prompt Box:
A prompt box is often used if you want the user to input a value
before entering a page.
When a prompt box pops up, the user will have to click either
"OK" or "Cancel" to proceed after entering an input value.
If the user clicks "OK" the box returns the input value. If the user
clicks "Cancel" the box returns null.
Syntax
[Link]("sometext","defaultText");
Functions
Functions are fundamental building blocks in all programming.
Functions are reusable block of code designed to perform a particular task.
Functions are executed when they are "called" or "invoked".
Syntax
function name( p1, p2, ... ) {
// code to be executed
}
Functions are defined with the function keyword:
followed by the function name
followed by parentheses ( )
followed by brackets { }
The function name follows the naming rules for variables.
Optional parameters are listed inside parentheses: ( p1, p2, ... )
Code to be executed is listed inside curly brackets: { }
Functions can return an optional value back to the caller.
Loops (for, while)
Loops are handy, if you want to run the same code over and over again, each time with
a different value.
For loop
Syntax:
var sum = 0;
for (var i = 0; i < 100; i++)
sum = sum + i;
Example:
while loops
The while loop loops through a block of code as long as a specified condition is true.
Syntax:
while (condition) {
statements;
}
For do while loop
do {
statements;
} while (condition);
Events
An event occurs as a result of some activity
o e.g.:
A user clicks on a link in a page
Page finished loaded
Mouse cursor enter an area
A preset amount of time elapses
A form is being submitted
Event Handlers
Event Handler – a segment of codes (usually a function) to be executed when an event occurs
We can specify event handlers as attributes in the HTML tags.
The attribute names typically take the form "onXXX" where XXX is the event name.
e.g.:
<a href="…" Website</a>
onClick Event Handler Example
<!DOCTYPE html>
<html>
<head>
<title>onClick Event Handler Example</title>
<script type="text/javascript">
function warnUser() {
return confirm("Are you a
student?");
</script>
</head>
<body>
<a href="[Link]" warnUser()">Students access only</a>
</body>
</html>
onLoad Event Handler
Example
<html><head>
<title>onLoad and onUnload
Event Handler
Example</title>
</head>
<body to this page')" for visiting this
page')"> Load and UnLoad event test. </body>
</html>
onMouseOver & onMouseOut Event Handler
<html>
<head>
<title>onMouseOver / onMouseOut Event Handler Demo</title>
</head>
<body>
<a href="[Link] Home'; return true;"
>
</body>
</html>
• When the mouse cursor is over the link, the browser displays the text "CUHK Home" instead of
the URL.
• The "return true;" of onMouseOver forces browser not to display the URL.
• [Link] and [Link] are disabled in Firefox.
onSubmit Event Handler Example
• If onSubmit event handler returns false, data is not submitted.
• If onReset event handler returns false, form is not reset
How to use “onError” event handler?
<html>
<head>
<title>onerror event handler example</title>
<script type="text/javascript">
function errorHandler(){
alert("Error Ourred!");
// JavaScript is casesensitive
// Don't write onerror!
[Link] = errorHandler;
</script>
</head>
<body>
<script type="text/javascript">
[Link]("Hello there;
</script>
</body>
</html>
Try … Catch
In JavaScript, the try statement is used to handle errors (also
called exceptions) that may occur during code execution - without
stopping the entire program.
The try statement works together with catch.
Sometimes it works with finally.
Syntax:
try {
// Contains normal codes that might throw an exception.
// If an exception is thrown, immediately go to
// catch block.
} catch ( errorVariable ) {
// Codes here get executed if an exception is thrown
// in the try block.
// The errorVariable is an Error object.
} finally {
// Executed after the catch or try block finish
// Codes in finally block are always executed
// One or both of catch and finally blocks must accompany the try block.
Example:
<script type="text/javascript">
try{
[Link]("Try block begins<br>");
// create a syntax error
eval ("10 + * 5");
} catch( errVar ) {
[Link]("Exception caught<br>");
// errVar is an Error object
// All Error objects have a name and message properties
[Link]("Error name: " + [Link] + "<br>");
[Link]("Error message: " + [Link] +
"<br>");
} finally {
[Link]("Finally block reached!");
</script>
Throw
The throw statement allows you to create a custom error.
Technically you can throw an exception (throw an error).
The exception can be a JavaScript String, a Number, a Boolean or
an Object:
throw "Too big"; // throw a text
throw 500; // throw a number
If you use throw together with try and catch, you can control program
flow and generate custom error messages.
Onerror
The onerror event is triggered if an error occurs while loading an external file (e.g. a document
or an image).
In HTML:
<element >
In JavaScript:
[Link] = function(){myScript};
In JavaScript, using the addEventListener() method:
[Link]("error", myScript);
Special Text:
Escape Characters
Because strings must be written within quotes, JavaScript will misunderstand this string:
let text = "We are the so-called "Vikings" from the north.";
The string will be chopped to "We are the so-called ".
To solve this problem, you can use an backslash escape character.
The backslash escape character (\) turns special characters into string characters:
Example:
String Length
To find the length of a string, use the built-in length property:
Example
Guidelines
Always use the same coding conventions for all your JavaScript projects.
JavaScript Coding Conventions
Coding conventions are style guidelines for programming. They typically cover:
Naming and declaration rules for variables and functions.
Rules for the use of white space, indentation, and comments.
Programming practices and principles.
Coding conventions secure quality:
Improve code readability
Make code maintenance easier
Variable Names
we use camelCase for identifier names (variables and functions).
All names start with a letter.
Example:
firstName = "John";
lastName = "Doe";
price = 19.90;
tax = 0.20;
fullPrice = price + (price * tax);
Spaces Around Operators
Always put spaces around operators ( = + - * / ), and after commas:
Examples:
let x = y + z;
const myArray = ["Volvo", "Saab", "Fiat"];
Code Indentation
Always use 2 spaces for indentation of code blocks:
Functions:
function toCelsius(fahrenheit) {
return (5 / 9) * (fahrenheit - 32);
}
Statement Rules
General rules for simple statements:
Always end a simple statement with a semicolon.
Examples:
const cars = ["Volvo", "Saab", "Fiat"];
const person = {
firstName: "John",
lastName: "Doe",
age: 50,
eyeColor: "blue"
};
General rules for complex (compound) statements:
Put the opening bracket at the end of the first line.
Use one space before the opening bracket.
Put the closing bracket on a new line, without leading spaces.
Do not end a complex statement with a semicolon.
Object Rules
General rules for object definitions:
Place the opening bracket on the same line as the object name.
Use colon plus one space between each property and its value.
Use quotes around string values, not around numeric values.
Do not add a comma after the last property-value pair.
Place the closing bracket on a new line, without leading spaces.
Always end an object definition with a semicolon.
Example
const person = {
firstName: "John",
lastName: "Doe",
age: 50,
eyeColor: "blue"
};
Java Objects
String
methods: charAt, charCodeAt, fromCharCode, indexOf, lastIndexOf, replace, split,
substring, toLowerCase, toUpperCase
charAt returns a one-letter String (there is no char type)
length property (not a method as in Java)
Strings can be specified with "" or ''
concatenation with + :
1 + 1 is 2, but "1" + 1 is "11"
Example:
var s = "Connie Client";
var fName = [Link](0, [Link](" ")); // "Connie"
var len = [Link]; // 13
var s2 = 'Melvin Merchant';
escape sequences behave as in Java: \' \" \& \n \t \\
converting between numbers and Strings:
var count = 10;
var s1 = "" + count; // "10"
var s2 = count + " bananas, ah ah ah!"; // "10 bananas, ah ah ah!"
var n1 = parseInt("42 is the answer"); // 42
var n2 = parseFloat("booyah"); // NaN
▰ accessing the letters of a String:
var firstLetter = s[0]; // fails in IE
var firstLetter = [Link](0); // does work in IE
var lastLetter = [Link]([Link] - 1);
Creating Objects
JavaScript is not an OOP language.
"prototype" is the closest thing to "class" in JavaScript.
Next few slides show several ways to create objects
It is also possible to emulate "inheritance" in JavasScript.
o See JavaScript and Object Oriented Programming (OOP)
Creating objects using new Object()
var person = new Object();
// Assign fields to object
"person"
[Link] = "John";
[Link] = "Doe";
// Assign a method to object
"person"
[Link] = function() {
alert("Hi! " + [Link] + " " + [Link]);
[Link](); // Call the method in "person"
Creating objects using Literal
Notation
var person = {
// Declare fields
// (Note: Use comma to
separate fields)
firstName : "John",
lastName : "Doe",
// Assign a method to object "person"
sayHi : function() {
alert("Hi! " + [Link] + " " +
[Link]);
[Link](); // Call the method in "person"
Date
Creating Date Objects
Date objects are created with the new Date() constructor.
There are 9 ways to create a new date object:
new Date()
new Date(date string)
new Date(year,month)
new Date(year,month,day)
new Date(year,month,day,hours)
new Date(year,month,day,hours,minutes)
new Date(year,month,day,hours,minutes,seconds)
new Date(year,month,day,hours,minutes,seconds,ms)
new Date(milliseconds)
JavaScript new Date()
new Date() creates a date object with the current date and time:
Array
An Array is an object type designed for storing data collections.
Key characteristics of JavaScript arrays are:
Elements: An array is a list of values, known as elements.
Ordered: Array elements are ordered based on their index.
Zero indexed: The first element is at index 0, the second at index 1, and so on.
Dynamic size: Arrays can grow or shrink as elements are added or removed.
Heterogeneous: Arrays can store elements of different data types (numbers, strings, objects
and other arrays).
var name = []; // empty array
var name = [value, value, ..., value]; // pre-filled
name[index] = value; // store element
Example:
var ducks = ["Huey", "Dewey", "Louie"];
var stooges = []; // [Link] is 0
stooges[0] = "Larry"; // [Link] is 1
stooges[1] = "Moe"; // [Link] is 2
stooges[4] = "Curly"; // [Link] is 5
stooges[4] = "Shemp"; // [Link] is 5
Array methods
array serves as many data structures: list, queue, stack, ...
methods: concat, join, pop, push, reverse, shift, slice, sort, splice, toString, unshift
push and pop add / remove from back
unshift and shift add / remove from front
shift and pop return the element that is removed
Example:
var a = ["Stef", "Jason"]; // Stef, Jason
[Link]("Brian"); // Stef, Jason, Brian
[Link]("Kelly"); // Kelly, Stef, Jason, Brian
[Link](); // Kelly, Stef, Jason
[Link](); // Stef, Jason
[Link](); // Jason, Stef
Boolean
The Boolean Data Type
In JavaScript, a Boolean is a primitive data type that can only have one of two values:
true or false
The Boolean value of an expression is the basis for all JavaScript comparisons and conditions.
Key Boolean Characteristics
true and false are boolean data types
true and false are the only possible boolean values
true and false must be written in lowercase
true and false must be written without quotes
Boolean Use Cases
Very often, in programming, you will need a data type that can represent one of two values, like:
yes or no
on or off
true or false
Math
methods: abs, ceil, cos, floor, log, max, min, pow, random, round, sin, sqrt, tan
properties: E, PI
Example:
var rand1to10 = [Link]([Link]() * 10 + 1);
var three = [Link]([Link]);
The 4 common methods to round a number to an integer:
RegExp
Regular Expressions
A Regular Expression is a sequence of characters that forms a search pattern.
Regex is a common shorthand for a regular expression.
JavaScript RegExp is an Object for handling Regular Expressions.
RegExp are be used for:
Text searching
Text replacing
Text validation
Syntax
/pattern/modifier flags;
HTML DOM
What is the DOM?
▻ It stands for Document Object Model
▻ With JavaScript, we can restructure an entire HTML document by adding, removing,
changing, or reordering items on a page
▻ JavaScript gains access to all HTML elements through the DOM
Comments
▰ identical to Java's comment syntax
▰ recall: 4 comment syntaxes
▻ HTML: <!-- comment -->
▻ CSS/JS/PHP: /* comment */
▻ Java/JS/PHP: // comment
▻ PHP: # comment
// single-line comment
/* multi-line comment */
Special values: null and undefined
undefined : has not been declared, does not exist
null : exists, but was specifically assigned an empty or null value
Why does JavaScript have both of these?
Example:
var ned = null;
var benson = 9;
// at this point in the code, ned is null ,benson's 9, caroline is undefined
Number type
integers and real numbers are the same type (no int vs. double)
same operators: + - * / % ++ -- = += -= *= /= %=
similar precedence to Java
many operators auto-convert types: "2" * 3 is 6
Example:
var enrollment = 99;
var medianGrade = 2.8;
var credits = 5 + 4 + (2 * 3);
Cookies
Relevance of Cookies
The communication between a web browser and server happens using a stateless protocol named HTTP.
Stateless protocol treats each request independent. So, the server does not keep the data after sending
it to the browser. But in many situations, the data will be required again. Here comes cookies into
picture. With cookies, the web browser will not have to communicate with the server each time the data
is required. Instead, it can be fetched directly from the computer.
Create, Access and Remove Cookies
You can create cookies using [Link] property like this.
[Link] = "cookiename=cookievalue"
You can even add expiry date to your cookie so that the particular cookie will be removed from the
computer on the specified date. The expiry date should be set in the UTC/GMT format. If you do not set
the expiry date, the cookie will be removed when the user closes the browser.
[Link] = "cookiename=cookievalue; expires= Thu, 21 Aug 2014 20:00:00 UTC“
You can also set the domain and path to specify to which domain and to which directories in the specific
domain the cookie belongs to. By default, a cookie belongs to the page that sets the cookie.
[Link] = "cookiename=cookievalue; expires= Thu, 21 Aug 2014 20:00:00 UTC; path=/ "
You can access the cookie like this which will return all the cookies saved for the current domain.
var x = [Link]
To delete a cookie, you just need to set the value of cookie to empty and set the value of expires to a
passed date.
[Link] = "cookiename= ; expires = Thu, 01 Jan 1970 00:00:00 GMT"
Internal & External JavaScript
Internal & External JavaScript
You can use JavaScript code in two ways.
• You can either include the JavaScript code internally within your HTML document itself
• You can keep the JavaScript code in a separate external file and then point to that file from your
HTML document.
External JavaScript
You plan to display the current date and time in all your web pages. Suppose you wrote the code and
copied into all your web pages (say 100). But later, you want to change the format in which the date or
time is displayed. In this case, you will have to make changes in all the 100 web pages. This will be a very
time consuming and difficult task.
So, save the JavaScript code in a new file with the extension .js. Then, add a line of code in all your web
pages to point to your .js file like this:
<script type="text/javascript" src="[Link]">
Data Validation
Data validation is the process of ensuring that user input is clean, correct, and useful.
Typical validation tasks are:
• has the user filled in all required fields?
• has the user entered a valid date?
• has the user entered text in a numeric field?
• Most often, the purpose of data validation is to ensure correct user input.
Validation can be defined by many different methods, and deployed in many different ways.
Server side validation is performed by a web server, after input has been sent to the server.
Client side validation is performed by a web browser, before input is sent to a web server.
Constraint Validation HTML Input Attributes