[Go to site: main page, start]

0% found this document useful (0 votes)
2 views84 pages

SE Web Chapter 4 JavaScriptv2

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)
2 views84 pages

SE Web Chapter 4 JavaScriptv2

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

Jimma University

Faculty of Computing and Informatics


Software Engineering Program

Web Design and Programming

Jimma, Ethiopia.
Introduction to JavaScript

❖ JavaScript is a high-level programming language that adds interactivity to your


website. This happens in games, in the behavior of responses when buttons are pressed
or with data entry on forms; with dynamic styling, with animation, etc.

▪ It is designed to add interactivity to HTML pages. It was invented by Brendan Eich


of Netscape/Mozilla

▪ It is a scripting language (a lightweight programming language)

▪ Usually embedded directly into HTML pages

▪ JavaScript gives HTML designers a programming tool

2
Cont...

❖ What can JavaScript Do?


▪ JavaScript can put dynamic text into an HTML page
▪ Running code in response to certain events occurring on a web page.
▪ JavaScript can read and write HTML elements
▪ JavaScript can be used to validate data
▪ Store useful values inside variables.
▪ 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

3
Cont...

❖ Note that JavaScript code did not need to be compiled

▪ JavaScript is an interpreted language

▪ A portion of the browser software that reads and executes JavaScript is an interpreter

❖ JavaScript can be run within a variety of environments:

▪ Web browsers

▪ Web servers

▪ Application containers (general-purpose programming)

4
Running the JavaScript

❖ Any time you include JavaScript in an HTML document, you must enclose it inside a
tag
<script >...</script>
▪ These tags alert the browser program to begin interpreting all the text between
these tags as a script.
❖ Other scripting languages such as VBScript also take advantage of these script tags
❖ Hence, you must specify the precise name of the language in which the enclosed code
is written to JavaScript.
▪ When the browser receives this signal, it employs its built-in JavaScript interpreter
to handle the code. (JavaScript interpreter: V8, Chakra, Spider monkey, and
JavaScript core webkit)
5
Cont...

<script language=”JavaScript” or lang=“JavaScript”>


//your script here
</script>
❖Here are some tips to remember when writing JavaScript commands:
▪ JavaScript code is case-sensitive (e.g. age and Age are different
variables)
▪ White space between words and tabs are ignored
▪ Line breaks are ignored except within a statement
▪ JavaScript statements end with a semi-colon (;)
6
Adding JavaScript

❖ There are three ways to add JavaScript commands to your Web Pages.
▪ Embedding code
▪ Inline code
▪ External file
I. External File
❖ If you want to run the same JavaScript on several pages, you can write the JavaScript in an
external file. Save the external JavaScript file with a .js file extension.
❖ The external script cannot contain the <script></script> tags!
❖ You can use the SRC attribute of the <SCRIPT> tag to call JavaScript code from an external
text file.
❖ It is called by the following tag:
<script lang=“text/JavaScript" src = "filename"> </script>
❖ The script tag should be placed in the HTML page's head
7
Cont...

II. Scripts in <head>


❖ Scripts to be executed when they are called, or when an event is triggered, are placed
in functions.
▪ Put your functions in the head section; this way, they are all in one place, and they
do not interfere with page content.
<head>
<script lang="javascript">
function message(){
alert("This alert box was called with the onload
event");
}
</script>
</head>
8
Cont.

III. Scripts in <body>


❖ If you don't want your script to be placed inside a function, or if your script should
write page content, it should be placed in the body section.
<html>
<head> </head>
<body>
<script lang="javascript">
[Link]("This message is written by JavaScript");
</script>
</body>
</html>
9
Basic JavaScript Syntax:

Input-Output in JavaScript
❖ In JavaScript, input-output can be done in different ways:
[Link](“message to display”);
alert(“message to display”);
prompt(“message to display”, “default value”);
confirm(“message to display”);
❖ [Link] method writes a string to the web page.

▪ Anything between double quotes will be displayed as it is on the web page.

▪ However, if there is something out of quotes, it is evaluated as an expression, and


the result will be sent to the web page.
10
Cont...

❖ The alert method produces a browser alert box.


▪ These are useful for debugging and learning the language. However, they are
not a good way to communicate with the users.
▪ alert() displays a modal window that presents a message to the user with a single
OK button to dismiss the dialog box.

11
Cont...

❖ The prompt display includes a message, a field for user input, and two buttons
(OK, and Cancel).
▪ The prompt(“”) returns a string of text entered by the user.
▪ It takes two parameters:
➢a message providing the prompt for the response, and
➢a default string that is used to fill in the text field.

12
Cont...

❖ A confirm dialog box presents a message in a modal dialog box along with OK and
Cancel buttons.
▪ Such dialog boxes can be used to ask the user a question, usually before
performing undoable actions.
▪ The dialog box returns a Boolean value of Ok=true; and Cancel=false;
❖ Example:
var adult = confirm(“Are you sure you are older than 18 years?”)
if(adult)
alert(“Yes”);
else
alert(“No”);
13
Working with Variables and Data

❖ In JavaScript, the value of a variable can be one of several types. The type of a
variable is dynamic: it depends on the type of data it contains.
❖ Table lists JavaScript’s formal data types, with examples of the values.

Type Example Description


String “John” a series of characters inside quotation marks
Number 4.5 any number not inside quotes
Boolean True a logical true or false
Null Null completely devoid of any value. Represents the intentional
absence of any object value.
Object Class that is defined by its properties and methods
Undefined Undefined (value of newly created variable). A variable has
been declared but has not been assigned a value.
14
Cont...

❖ To declare a variable, we use the var, let, and const keywords, followed by the name of the
variable.
❖ Therefore, to declare a new variable called myAge:
var myAge;
❖ Apply variable declaration rules: Must begin with letter or underscore ( _ ), Must contain only
letters, underscores, and digits (or certain other characters), and not be a reserved word
❖ It is possible to assign a value using an equal (=) sign. JavaScript is loosely typed.
❖ Variables can store any type of data. var value=“Hello world!”; value = 30.5;
❖ The typeof operator returns a string related to the data type
❖ Syntax: typeof expression

15
Values returned by typeof for various operands

❖ A variable will automatically be created if a value is assigned to an undeclared


identifier:
16
Comments

❖ JavaScript supports two types of comments:


▪ Comments on a single line are preceded by //.
▪ Comments that span multiple lines are preceded by /* and followed by */
❖ Example: the following example shows two comments:
//This next line prints text into the document
[Link]("This line came from some JavaScript");
/* This is a multiple-line comment. This line shows an
alert so we know things worked properly */
alert("The text has been printed");

17
Operators and Expressions

❖ An operator performs some kind of calculation (operation) or comparison with two values
to reach a third value.
❖ Generally, operators can be broadly categorized into four:
▪ Arithmetic operators, ❖ Operators are used to create compound expressions
▪ Assignment operators from simpler expressions
❖ Operators can be classified according to the
▪ Comparison operators and
number of operands involved:
▪ Logical operators. Unary: one operand (e.g., typeof i)
Prefix or postfix (e.g., ++i or i++ )
Binary: two operands (e.g., x + y)
Ternary: three operands (conditional operator)

18
Cont...
Arguments can be any expressions

Comments like Java/C++ (/* */ also allowed)

Variable declarations:
- Not required
- Data type not specified
Semi-colons are usually
not required, but always
allowed at statement end

Arithmetic operators same as Java/C++ String concatenation operator


as well as addition
Argument lists are comma-separated

19
Data Type Conversions

❖ The type of data in an expression can trip up some script operations if the expected
components of the operation are not of the right data type.
▪ JavaScript tries its best to perform internal conversions to head off such problems.
❖ In a simple arithmetic statement that adds two numbers together, you get the expected result:
3 + 3; // result = 6
3 + “3” // result = “33”
3 + 3 + “3” // result = “63”
❖ JavaScript provides two built-in functions to convert string representations of numbers to true numbers:
▪ parseInt(string [,radix]) ▪ parseInt(“42”) // result = 42
▪ parseFloat(string [,radix]) ▪ parseInt(“42.33”) // result = 42
➢ radix, which is optional, specifies the base of the number to convert to: hexadecimal, octal, or
decimal.

20
Automatic Type Conversion

❖ Binary operators +, -, *, /, % convert both operands to Number


▪ Exception: If one of the operands of + is String then the other is converted to String
❖ Relational operators <, >, <=, >= convert both operands to Number
▪ Exception: If both operands are String, no conversion is performed and lexicographic string
comparison is performed
❖ Operators ==, != convert both operands to Number
▪ Exception: If both operands are String, no conversion is performed (lex. comparison)
▪ Exception: values of Undefined and Null are equal
▪ Exception: two Objects are equal only if they are references to the same object
❖ Operators ===, !== are strict:
▪ Two operands are === only if they are of the same type and have the same value
❖ Unary +, - convert their operand to Number
❖ Logical &&, ||, ! convert their operands to Boolean
21
Working with Conditional Statements

❖ Conditional statements are used to perform different actions based on conditions.


❖ Broadly, there are two ways to execute code conditionally:
▪ If statement switch (fruittype) {
case "Apples":
▪ switch statement [Link]("Apples are $0.32 a pound.<br>");
break;
Example: case "Bananas":
if (myAge < 18) { [Link]("Bananas are $0.48 a pound.<br>");
alert(“Sorry, you cannot vote.”) break;
} case "Mangoes":
case "Papayas":
[Link]("Mangoes and papayas are $2.79 a
pound.<br>");
break;
default:
[Link]("Sorry, we are out of " + fruittype + ".<br>");
22 }
Working with Loops

❖ A loop is a set of commands that executes repeatedly until a specified condition is


met.
❖ JavaScript supports the for, do while, and while loop statements.
▪ In addition, you can use the break and continue statements within loop statements.
❖ Another statement, for...in, executes statements repeatedly but is used for object
manipulation.
❖ There are three loop statements in JavaScript:
▪ for Statement
▪ do...while Statement
▪ while Statement

23
Cont...

A for loop repeats until a specified condition A do...while statement looks as follows:
evaluates to false. var i=1;
var counter = 10; do{
var sum = 0; [Link](i);
for (var i = 0; i <= counter; i++) { i += 1;
sum = sum + i; } while (i < 5);
}
[Link](“the sum is ” + sum);
A while statement looks as follows:
while (condition)
{
statement
}

24
Cont...

Many control constructs and use of


{ } identical to Java/C++
Most relational operators syntactically
same as Java/C++

Automatic type conversion:


guess is String,
thinkingOf is Number

25
JavaScript keyword statements are very
similar to Java with small exceptions

26
Functions in JavaScript

❖ Functions are one of the fundamental building blocks in JavaScript.


❖ A function is a set of statements that performs a specific task.
❖ To use a function, you must first define it, then your script can call it.
Declaration
Defining Functions always begins
❖ A function definition consists of a function keyword, followed by: with keyword
function,
▪ The name of the function. no return type
▪ A list of arguments to the function, separated by commas.
▪ The statements that define the function, enclosed in curly braces { }.
❖ The syntax to define function: Identifier representing function’s name
function functionName ( [parameter1]...[,parameterN] ) {
statement[s] Formal parameter list
} One or more statements representing function body
27
Cont...

❖ Function names have the same restrictions as variable names.


▪ It is possible to use multiword names with the interCap format that start with a verb because
functions are action items.
❖ Example: the following code defines a simple function named square:
function square(number) {
return number * number;
}
❖ Arrow function useful for writing shorter function expressions

const add = (a, b) => {


const functionName = (parameters) => {
return a + b;
// function body
};
};
[Link](add(2, 3)); // Output: 5
28
Cont...

❖ Function expression
( () => {
const mult= function(a,b){
[Link](“Arrow IIFE!”);
return a*b; }) ();
}
❖ Anonymous function: function without a name often used as arguments in other function
functions.
▪ (function(){ (function(name){
[Link](“Runs immediately!”); [Link](“Hello ”+ name);
}) (“Abebe”);
}) ();
▪ Called immediately invoked function expressions. Instead of waiting to be called later the
function executes right away.
▪ It is useful for setup tasks that should run once
29
Cont...

❖ JavaScript checks neither the type nor number of parameters in a function call
▪ Formal parameters have no type specified
▪ Extra actual parameters are ignored
▪ If there are fewer actual parameters than formal parameters, the extra formal
parameters remain undefined
❖ This flexibility is typical of many scripting languages different numbers of parameters
may be appropriate for different uses of the function.

function greet(name) { const mult = function add(a, b) {


[Link]('Hello, ' + name + '!'); return a + b;
} }
greet(); // Output: Hello, undefined! [Link](add(5, 10, 15)); // Output: 15
30
Cont...

▪ The example below returns the product of two numbers (a and b):
<html><head>
<script language=“JavaScript"> function sum() {
function product(op1, op2){ let total = 0;
return op1*op2; for (let i = 0; i < [Link]; i++) {
} total += arguments[i];
</script> }
return total;
</head><body>
}
<script language=“JavaScript">
[Link](sum(1, 2, 3, 4)); //
[Link](product(4,3));
Output: 10
</script>
</body></html>
31
Arrays

❖ The Array built-in object can be used to construct objects with special properties that
inherit various methods
❖ An array is an ordered collection of data. Array in JavaScript is heterogeneous can
store number, string, objects or even other array.
❖ To initialize an array for your script, use the new keyword to construct the object for
you while assigning the array object to a variable of your choice:
❖ var myArray = new Array(n); where n is the number of entries you anticipate for the
array.
Example: an array that stores the names of planets ary1
length (0) Properties
var planet = new Array(3); //an array with 3 entries
planet[0] = “Mercury” toString() Inherited
planet[1] = “Venus” sort() methods
shift()
planet[2] = “Earth” …
32
Cont...

❖ You can also create array by directly giving the values:


▪ var planet = new Array(“Mercury”, ”Venus”, ”Earth”, ”Mars”, “Jupiter”, “Saturn”,
”Uranus”, ”Neptune”, ”Pluto”);
❖ You can also create the planets array like:
▪ var planet = [“Mercury”, ”Venus”, ”Earth”, ”Mars”, “Jupiter”, “Saturn”,
”Uranus”, ”Neptune”, ”Pluto”];
❖ In general, you can create an array in three different ways :
arrayName = new Array(arrayLength);
arrayName = new Array(element0, element1, ..., elementN);
arrayName = [element0, element1, ..., elementN];
33
Cont...

Access an Array
❖ You can use the [Link]() method to display all the content of the Array.
❖ This will produce one long text string that is composed of each element of the array
like this:
▪ [Link](planet);
❖ This produces the following output:
▪ Mercury, Venus, Earth, Mars, Jupiter, Saturn, Uranus, Neptune, Pluto
❖ You can refer to a particular element in an array by using the index number.
▪ The index number starts at 0 and ends at n-1 for an array of n entries.
❖ For example, to access the fifth planet in the planet’s array, we use:
▪ [Link](planet[4]); //prints Jupiter
34
Cont...

❖ To output each element of the array individually, you can set up a for () statement like this:
for (var i=0; i < [Link]; i++) {
[Link](planet[i] + "<BR>"); }
Deleting Array Entries
❖ You can always set the value of an array entry to null or an empty string to wipe out the data.
▪ But with the delete operator, you could not completely remove the element.
❖ Deleting an array element eliminates the index from the list of accessible index values
▪ But it does not reduce the array’s length
[Link]; // result: 9
delete planet[2];
[Link]; //result: 9
[Link](planet[2]); //result: undefined
35
Method Description
filter() Creates a new array with all of the elements of this array for which the provided filtering
function returns true.
indexOf(value) Returns the first (least) index of an element within the array equal to the specified value, or
-1 if none is found.
join(separator) Joins all elements of an array into a string using separator
lastIndexOf(value) Returns the last (greatest) index of an element within the array equal to the specified value,
or -1 if none is found.
pop() Removes the last element from an array and returns that element.
push(value) Adds one or more elements to the end of an array and returns the new length of the array.
reverse() Reverses the order of the elements of an array − the first becomes the last, and the last
becomes the first.
shift() Removes the first element from an array and returns that element.
slice(start [,end]) Extracts a section of an array and returns a new array.
splice(start [,deletecount Replaces and/or removes elements from an array.
[,item1 [,item2 [,…itemN]]]]))
toString() Returns a string representing the array and its elements.
unshift(value) Adds one or more elements to the front of an array and returns the new length of the array.
36
Cont...

function arrayFunction() { [Link]("<br>Search 80: " +


[Link]("80"));
var grade = new Array("70", "60", "80",
"90", "20"); [Link]("<br>Converted to string: "
+ [Link]());
[Link]("<br> Popped: " +
[Link]()); var slicedValue = [Link](2);
[Link]("<br> After poping:"); [Link]("<br>Sliced: " +
slicedValue);
for(var i=0;i<[Link]; i++)
[Link]("<br>Spliced: " +
[Link](" " + grade[i]);
[Link](1));
[Link]();
[Link]("500","6000");
[Link]("<br>Reversed: ");
[Link]("<br>Final: " + grade);
for(var i=0;i<[Link]; i++)
}
[Link](" " + grade[i]);

37
Cont...

❖This produces the following let numbers = [1,2,3,4,5,6];


output: let even = [Link]( num=>num%2===0 )
//70, 60, 80, 90, 20
let fruits = [“Appel”, “Banana”, “Mango”, “Avocado”];
Popped: 20 let afruits = [Link](fruit=>[Link](“A”));
After poping: 70 60 80 90 [Link](afruits)
Reversed: 90 80 60 70
let students =[
Search 80: 1 {name:”Abeba”, score:85},
Converted to string: 90,80,60,70 {name:”Chala”, score:45},
{name:”Kebede”, score:95}
Sliced: 60,70
];
Spliced: 80,60,70 let passed = [Link](student => [Link]
Final: 500,6000,90 >=50);
[Link](passed)
38
JavaScript Objects and Events

Managing Events

▪ Events are occurrences generated by the browser, such as loading a document, or


by the user, such as moving the mouse, clicking a button, pressing a key; that the
browser detects and allows your code to respond to.

▪ They are the user and browser activities to which we may respond dynamically
with a scripting language like JavaScript.

▪ There are several more events that we can capture with JavaScript, but the ones
below are, by far, the most popular.

39
Event Event Handler Description
Load onLoad Browser finishes loading a Web document
Unload onUnload Visitor requests a new document in the browser window
Mouseover onMouseOver Visitor moves the mouse over some object in the document window
Mouseout onMouseOut Visitor moves the mouse off of some object in the document window
MouseDown onMouseDown A mouse button was pressed
MouseMove onMouseMove The mouse moved
MouseUp onMouseUp The mouse button was released
Select onSelect Text has been selected.
Click onClick Visitor clicks the mouse button
Focus onFocus Visitor gives focus to or makes active a particular window or form element by
clicking on it or tabbing to it
Blur onBlur A form field lost the focus (user moved to another field)
Change onChange Visitor changes the data selected or contained in a form element
Submit onSubmit Visitor submits a form
Reset onReset Visitor resets a form
Abort onAbort An image failed to load
Change onChange The contents of a field has changed
DblClick onDblClick User double-clicked on this item
Error onError An error occurred while loading an image
Keydown onKeyDown A key was pressed
KeyPress onKeyPress A key was pressed or released
40
KeyUP onKeyUp A key was released
Cont...

❖ Example: a program that adds or [Link]("The difference is " +


subtracts two numbers when the difference);
respective button is clicked }
<html><head> </script>
<script language="JavaScript"> </head><body>
function adder(num1, num2){ <form name="event_example">
var sum = 0; <input type="button" value="add" name="add"
sum = num1 + num2; > [Link]("The sum is " + sum); <input type="button" value="subtract"
name="subtract"
} > function subtractor(num1, num2){ <a href=“” Add </a>
var difference = 0; </form></body></html>
difference = num1 - num2;
41
JavaScript objects

❖ JavaScript has a powerful and flexible object model.


▪ Unlike the Java programming language, JavaScript is a classless language:
➢the behavior and state of an object are not defined by a class, but rather by other
objects (in the case of JavaScript, this object is called the object's prototype).
❖ An object is a dynamic data structure that store related data and functionality as key—value
pairs. It is object groups data and behavior together.
❖ Example (from Netscape’s documentation):
▪ car = {myCar: "Saturn", 7: "Mazda", getCar: CarTypes("Honda"), special: Sales}
▪ The fields are myCar, getCar, 7 (this is a legal field name), and special
▪ "Saturn" and "Mazda" are Strings
▪ CarTypes is a function call
▪ Sales is any defined variable

42
➢Example use: [Link]("I own a " + [Link]);
Three ways to create an object

❖ You can use an object literal:


– var course = { number: "CIT597", teacher="Dr. Dave" } [Link] = 4;
❖ You can use new to create a “blank” object, and add fields to it later:
– var course = new Object();
[Link] = "CIT597";
[Link] = "Dr. Dave";
– [Link](“the course number is “+[Link] +”the course
teacher is ”+[Link] );
❖ You can write and use a constructor:
– function Course(n, t) { // best placed in <head>
[Link] = n;
[Link] = t;
}
– var course = new Course("CIT597", "Dr. Dave");
43
Cont...

❖ JavaScript has many built-in objects that you can use to perform different activities.
▪ Every time you load a page into a web browser, the JavaScript interpreter creates certain
objects based on how the HTML is written.
➢This minimal object set is comprised of the navigator, window, document, location,
and history objects.
❖ Depending on what's contained in the page, there can be other Objects that are also generated
by the interpreter.
▪ All of these Objects exist in an Object hierarchy that can be accessed by calling on the
Object with dot notation.
❖ The following chart shows the structure.

44
45
Cont...

Object Properties and Methods


❖ A property of an object is basically a predefined variable that you can assign a value
to with simple dot notation. Syntax like this:
[Link] = value;
❖ For instance, if you want to change the background color of the document Object to
blue, you would access the bgColor Property and assign the String "blue" to it like
this:
[Link] = "blue“;
❖ A method of an object is a predefined function that is assigned to an Object by a
browser.
❖ You invoke a method on an object with the same dot notation like this:
[Link]();
46
Date object

Date Object
❖ Most of the date and time work is done with the Date object.
❖ The basic syntax for generating a new date object is as follows:
var dateObjectName = new Date([parameters])
❖ The parameter can be:
new Date(“Month dd, yyyy hh:mm:ss”)
new Date(“Month dd, yyyy”)
new Date(yy,mm,dd,hh,mm,ss)
new Date(yy,mm,dd)
By default, JavaScript will use the browser's time zone and display a date as a full text
string:
47
Method Value Range Description
[Link]() 0-... returns Milliseconds since 1/1/70 00:00:00 GMT
[Link]() 70-... returns Specified year minus 1900
returns four-digit year for 2000+
[Link]() 1970-... returns four-digit year
[Link]() 0-11 returns Month within the year (January = 0)
[Link]() 1-31 returns Date within the month
[Link]() 0-6 returns Day of week (Sunday = 0)
[Link]() 0-23 returns Hour of the day in 24-hour time
[Link]() 0-59 returns Minute of the specified hour
[Link]() 0-59 returns Second within the specified minute
[Link](val) 0-... sets Milliseconds since 1/1/70 00:00:00 GMT
[Link](val) 70-... sets Specified year minus 1900
sets four-digit year for 2000+
[Link](val) 0-11 sets Month within the year (January = 0)
[Link](val) 1-31 sets Date within the month
[Link](val) 0-6 sets Day of week (Sunday = 0)
[Link](val) 0-23 sets Hour of the day in 24-hour time
[Link](val) 0-59 sets Minute of the specified hour
48
[Link](val) 0-59 sets Second within the specified minute
Cont...

❖ Example: display current date and time


var today = new Date();//browser current date and time
var date = [Link]();
var month = [Link]();
var year = [Link]();
[Link](“Today’s date: ”+date+”/”+month+”/”+year);
output: Today’s date: 09/01/2025
❖ Example: to set date to some past time like birth date
var myBirthday = new Date(“September 11, 2001”);
result = [Link](); // result = 2, a Tuesday
[Link](2002); // bump up to next year
result = [Link](); // result = 3, a Wednesday

49
String object

String Object
❖ JavaScript strings are for storing and manipulating text.
▪ JavaScript imposes no practical limit on the number of characters that a string can hold.
❖ You have two ways to assign a string value to a variable.
▪ The simplest is a basic assignment statement:
var myString = “Hello there.”;
▪ You can also create a string object using the more formal syntax that involves the new
keyword and a constructor function like:
var stringVar = new String(“characters”);

50
Method Description
charAt(index) Returns the character at the specified index.
charCodeAt(index) Returns a number indicating the Unicode value of the character
at the given index.
concat(string) Combines the text of two strings and returns a new string.
indexOf(string, [start]) Returns the index within the calling String object of the first
occurrence of the specified value, or -1 if not found.
lastIndexOf(string,[start]) Returns the index within the calling String object of the last
occurrence of the specified value, or -1 if not found.
localeCompare(string2) Returns a number indicating whether a reference string comes
before or after or is the same as the given string in sort order.
Length Returns the length of the string.
match(regExpression) Used to match a regular expression against a string.
51
replace(regExpression Used to find a match between a regular expression and a string, and
,replacer) to replace the matched substring with a new substring.
search(regExpression) Executes the search for a match between a regular expression and a
specified string.
slice(startIndex [,end]) Extracts a section of a string and returns a new string.
split(delimiter [,limit]) Splits a String object into an array of strings by separating the string
into substrings.
substr(start [, length]) Returns the characters in a string beginning at the specified location
through the specified number of characters.
substring(start, end) Returns the characters in a string between the two indexes into a
string.
toLowerCase() Returns the calling string value converted to lower case.
toUpperCase() Returns the calling string value converted to uppercase.
toString() Returns a string representing the specified object.
52
Cont…

❖ Example:
var name = new String(“Konrad Zuse”);
[Link](“ - created the first computer”);
[Link](0,10);
[Link](“Zuse”);
[Link](“a”,”#”);
[Link]();
❖ Output:
Konrad Zuse - created the first computer
Konrad Zuse
7
Konr#d Zuse
KONR#D ZUSE

53
Document object

Document Object
❖ Contains information on the current document.
❖ Document object contains properties and methods that can be used to access the page elements.
❖ Properties:
▪ title - Current document title. If no title is defined, title contains “Untitled.”
▪ location - Full URL of the document.
▪ lastModified - A Date object-compatible string containing the date the document was last modified.
▪ bgColor - Background color, expressed as a hexadecimal RGB value (for example, #FFFFF for
white). Equivalent to the BGCOLOR attribute of the <BODY> tag.
▪ fgColor - Foreground (text) color, expressed as a hexadecimal RGB value compatible with HTML
syntax. Equivalent to the TEXT attribute of the <BODY> tag.
▪ linkColor - Hyperlink color, expressed as a hexadecimal RGB value compatible with HTML
syntax. Equivalent to the LINK attribute of the <BODY> tag.

54
Cont...

❖ alinkColor - Activated hyperlink color, expressed as a hexadecimal RGB value. Equivalent to the ALINK
attribute of the <BODY> tag.
❖ vlinkColor – visited link color, expressed as hexadecimal RGB value
❖ forms[] - Array of form objects in the document, in the order specified in the source. Each form has its own
form object.
❖ [Link] - The number of form objects within the document.
❖ links[] - Array objects corresponding to all HREF links in the document, in the order specified in the source.
❖ [Link] - The number of HREF links in the document.
❖ anchors[] - Array of all "named" anchors between the <A NAME=""> and </A> tags within the document.
❖ [Link] - The number of named anchors in the document.
❖ images[] - Image objects that correspond to each image on the page.
❖ applets[] - Java applet objects that correspond to each applet on the page.
❖ embeds[] - Plugins object that represent each plug-in on the page.
55
Cont...

❖ Example: changing link colors


[Link] = “red”;
[Link] = “blue”;
[Link] = “green”;
❖ Methods:
▪ write("string") - writes string to the current window. string may include HTML tags.
▪ getElementById(name)
▪ getElementsByTagName (name)
▪ getElementsByClassName (name) Reading Assignment
▪ clear( ) - Clears the window. History Object
▪ close( ) - Closes the window.
Number Object
▪ createElement(element)
56
Window Object

Window Object
❖ At the very top of the document object hierarchy is the window object.
▪ It is the master container for all content you view in the Web browser.
❖ Methods:
❖ [Link]() - this method opens a new window.
❖ The syntax is:
[Link](“URL”, “name” [, “windowfeatures”]);
❖ Parameters:
▪ URL is a string that points to the window you want to open
▪ name is a string that names the new window

57
Cont...

❖ windowfeatures is one or more of the following in a comma-separated list:


▪ toolbar - toolbar is present. The value is yes or no.
▪ location – Location bar is present. The value is yes or no.
▪ directories
▪ status – statusbar is present. The value is yes or no.
▪ menubar – menubar is present. The value is yes or no.
▪ scrollbars – scrollbars are present. The value is yes or no.
▪ resizable – window is resizable. The value is yes or no.
▪ copyhistory
▪ width – width of the window
▪ height – height of the window
[Link](“[Link]”, “testing ”, “toolbar=yes,status=yes”);
58
Cont...

❖ In a more controlled way using windowfeatures:


newWin=[Link]("", "New", "height=250, width=250, toolbar=no,
scrollbars=yes, menubar=no");
[Link](“\<TITLE\>Title Goes Here\</TITLE\>");
[Link]("\<BODY BGCOLOR=red\>");
[Link]("\<h1\>Hello! \</h1\>");
[Link]("This text will appear in the window!");
[Link]("\</BODY\>");
[Link]("\</HTML\>");
[Link]();

59
[Link](message) Displays an alert dialog.
[Link]() Moves back one in the window history.
[Link]() Sets focus away from the window.
[Link](([Link]) Registers the window to capture all specified events.
[Link](intervalID) Clears a delay that’s been set for a specific function.
[Link](timeoutID) Clears the delay set by [Link]().
[Link]() Closes the current window.
[Link](message) Displays a dialog with a message that the user needs to respond to.
[Link](message) Writes a message to the console.
[Link](text) Encodes a string.
[Link]() Sets focus on the current window.
[Link]() Moves the window one document forward in the history.
[Link]() Flashes the application icon to get user attention.
[Link]() Returns the selection object representing the selected item(s).
[Link]() Returns the browser to the home page.
[Link](pixelX, pixelY) Moves the current window by a specified amount.
[Link](x, y) Moves the window to the specified coordinates.
60
[Link](URL,name[,features]) Opens a new window.
[Link]() Prints the current document.
[Link](message[,default]) Returns the text entered by the user in a prompt dialog.
[Link]([Link]) Releases the window from trapping events of a specific type.
[Link](pixelX, pixelY) Resizes the current window by a certain amount.
[Link](iWidth, iHeight) Dynamically resizes window.
[Link](x-coord, y-coord) Scrolls the window to a particular place in the document.
[Link](pixelX, pixelY) Scrolls the document in the window by the given amount.
[Link](lines) Scrolls the document by the given number of lines.
[Link](pages) Scrolls the current document by the specified number of
pages.
[Link](x-coord, y-coord) Scrolls to a particular set of coordinates in the document.
[Link](cursortype) Changes the cursor.
[Link](“funcName”, delay) Set a delay for a specific function.
[Link](“funcName”, delay) Sets a delay for executing a function.
61
Image Object

Image Object
❖ The Image object reflects the attributes of an image on the current page.
❖ An image on the page can be referred to either via the images[] array or by the image name, as shown here:
[Link][2].propertyName
[Link]
❖ Properties
▪ length - Reflects how many images are in the page (e.g. [Link]).
▪ border - Reflects the BORDER attribute
▪ complete - Boolean value indicating whether Navigator has completed its attempt to load the image
▪ height - Reflects the HEIGHT attribute and width - Reflects the WIDTH attribute.
▪ hspace - Reflects the HSPACE attribute and vspace - Reflects the VSPACE attribute.
▪ lowsrc - Reflects the LOWSRC attribute.
▪ name - Reflects the NAME attribute.
▪ src - Reflects the SRC attribute (can dynamically change the image on a page).

62
Cont...

Example: image slide show using JavaScript


<html><head>
<script language="JavaScript">
var photonames = new Array('[Link]', '[Link]', 'Ethiopia_regions.png', ‘[Link]', '[Link]');
var tt = setInterval("slideshow()", 2000);
Var currentphoto = 0;
function slideshow(){
currentphoto++;
if(currentphoto > [Link] - 1)
currentphoto = 0;
[Link] = photonames[currentphoto];
}
</script></head>
<body>
<img src="[Link]" id="photo" height="80%"> <br>
</body></html>

63
Form Processing and Validation

❖ It is possible to access form and form elements from JavaScript.


▪ You can set attributes for NAME, TARGET, ACTION, METHOD, and ENCTYPE
for form.
➢Each of these is a property of a FORM object, accessed by all lowercase
versions of those words, as in:
[Link][0].action //forms array of the document
[Link] //references exact form by name
❖ To change any of these properties, simply assign new values to them:
[Link] = “[Link]”

64
Cont...

❖ Forms support different events:


▪ onFocus – an event is triggered with a form object gets input focus.
▪ onBlur – this event is triggered when a form object loses input focus.
▪ onChange – an event is triggered when a new item is selected in a list box.
➢This event is also trigged with a text or text area box loses focus and the contents of
the box has changed.
▪ onSelect – an event is triggered when text in a text or text area box is selected.
▪ onSubmit – an event is triggered when the form is submitted to the server.

65
Accessing Form Elements

❖ You can read data from or set data to form elements like text field, text area, check box,
etc. in many different ways:
▪ using form name & element name
▪ using forms array & element name
▪ using id of the element
❖ The syntax is as follows:
value = [Link][0].[Link]; //read content
[Link][0].[Link] = newValue; //set content
❖ You can use form name to access form elements using the following syntax:
value = [Link]; //read content
[Link] = value; //set content
❖ It is also possible to use forms array of document object to access form elements.
66
Cont...

❖ It is also possible to use getElementById() method of JavaScript to access form


elements.
❖ The getElementById() method is used to retrieve an element by using its ID.
▪ The ID is a unique identifier that is assigned to an element in the HTML code.
❖ The getElementById() method takes the ID as a parameter and returns the element
object.
❖ The syntax to access the form elements is:
value = [Link](“form element id”).value; //to read
[Link](“form element id”).value = value; //to set

67
function add() {
var op1 = [Link]; //using form name directly
var op2 = [Link][0].[Link]; //using forms array
var sum = op1 + op2;
[Link]("result").value = sum; //using id of the element
}

<FORM NAME="test" ACTION="[Link]" METHOD="get">


First number: <INPUT TYPE="text" NAME="fnum" ID="fnum"><br>
Second number: <INPUT TYPE="text" NAME="snum" ID="snum"><br>
Result: <INPUT TYPE="text" NAME="result" ID="result"><br>
<INPUT TYPE="button" NAME="adder" Value="Add" >

68
Cont...

Text boxes and Text areas


❖ Text fields have a value property.
▪ The value property of the input text box, is both readable and writable.
❖ To access text input fields, you can use the syntax:
value = [Link]; //read content
[Link] = value; //set content
❖ Text box and textarea properties:
▪ name - String value of the NAME attribute.
▪ value - String value of the contents of the field.
▪ defaultValue - String value of the initial contents of the field.
▪ type - Specifies what type of object this form field is (e.g. “text” or “Textarea”).
69
<HTML><HEAD><TITLE>Test Input</TITLE>
<SCRIPT LANGUAGE="JavaScript">
function hello () {
var urname = [Link];
var gender;
if([Link][0].checked)
gender = [Link][0].value;
else if([Link][1].checked)
gender = [Link][1].value;
alert ("Hello, " + urname + "! Your are "+ gender);
}
</SCRIPT></HEAD> <BODY>
<FORM NAME="test" ACTION="" METHOD="GET">
Enter your name: <INPUT TYPE="text" NAME="name"><br>
Gender: <INPUT TYPE="radio" NAME=“gender" Value="Male">Male<BR>
<INPUT TYPE="radio" NAME=" gender " Value="Female">Female<BR>
<INPUT TYPE="button" NAME="button" Value="Say Hello" > 70
</FORM></BODY></HTML>
Cont...

❖ With the help of JavaScript, the form input can easily be checked before sending it over the
Internet.
▪ It is sent only if the input is valid.
❖ Form data that is typically checked by JavaScript could be:
▪ has the user left required fields empty?
▪ has the user entered a valid e-mail address?
▪ has the user entered a valid date?
▪ has the user entered text in a numeric field?

71
<html> <head>
<script language="JavaScript">
function check(form) {
if ([Link] == "")
alert("Please enter a string as your name!")
if([Link] < 0 || [Link]=="")
alert("Age should be number and greater than 0");
if ([Link] == "" || [Link]('@', 0) == -1)
alert("No valid e-mail address!");
if([Link]=="")
alert("No message written");
}
</script></head> <body>
<h2> <u> Form validation </u> </h2>
<form name="first">
Enter your name: <input type="text" name="urname"> <br>
Enter your age: <input type="text" name="age"> <br>
Enter your e-mail address: <input type="text" name="email"> <br>
write message: <textarea name="urmessage" cols=40 rows=10></textarea><br><br>
<input type="button" name="validate" value="Check Input" ></body></html>

72
HTML DOM

❖ The Document Object Model, which is normally referred to as the DOM, models all of the
parts of a web page document as nodes in a node tree.
▪ Each node represents either (1) an element, (2) a text item that appears between an
element’s start and end tags, or (3) an attribute within one of the elements.
❖ Every element on an HTML page is accessible in JavaScript through the DOM: Document
Object Model
▪ Can modify, add, and remove nodes on the DOM, which will modify, add, or remove the
corresponding element on the page.
❖ When a web page is loaded, the browser creates a Document Object Model of the page.

73
Cont…

74
HTML DOM

❖ With the object model, JavaScript gets all the power it needs to create dynamic HTML:
▪ It can change all the HTML elements on the page
▪ It can change all the HTML attributes on the page
▪ It can change all the CSS styles on the page
▪ It can remove existing HTML elements and attributes
▪ It can add new HTML elements and attributes
▪ It can react to all existing HTML events on the page
▪ It can create new HTML events on the page

75
HTML DOM

❖ The document object represents your web page. If you want to access any element in an
HTML page, you always start with accessing the document object.
❖ Then you can do a lot of things with the document object:

Action Example

Finding HTML Elements [Link](CSS selector);

Adding and Deleting Elements [Link](element);

Changing HTML Elements [Link] = new html content;

Adding Events Handlers [Link]('event', handler);

76
HTML DOM

❖ Finding HTML Elements


▪ If you want to find the first HTML elements that match a specified CSS selector (id,
class names, types, attributes, values of attributes, etc), use the querySelector() method.
❖ For example, this JavaScript statement will return the first paragraph element of class main:
❖ [Link]("[Link]"); <body>
<p>my first paragraph</p>
❖ [Link]("[Link]"); <p class="main">my first main paragraph</p>
<p class="main">my second main paragraph</p>
<a href="[Link]
</body>

❖ querySelectorAll() method will return a list of all HTML elements that match the specified
CSS query.
▪ const pars = [Link]("[Link]");
➢pars[0], pars[1]
77
HTML DOM

❖ Changing HTML Elements


▪ The HTML DOM allows JavaScript to change the content of HTML elements
▪ The easiest way to modify the content of an HTML element is by using the innerHTML
property.
❖ To change the content of an HTML element, use this syntax:

• For example this JavaScript code changes the text inside the h1 element:
let header = [Link]("h1");
[Link] = "My new heading";

78
HTML DOM

❖ You can also change the value of an HTML attribute.

For example, this javascript code changes the href attribute of an <a> element with id myLink:
let myLink = [Link]("#myLink");
[Link] = "[Link]

79
HTML DOM

❖ Changing CSS properties


▪ To change the style of an HTML element, use this syntax:

For example, this JavaScript code changes the font size of the second <p> element with class par
to twice its default value:
let pars = [Link]("[Link]");
pars[1].[Link] = "2em";

80
HTML DOM

❖ Adding HTML Elements


▪ To add a new element to the HTML DOM, you must create the element (element node)
first, and then append it to an existing element

81
HTML DOM

❖ <div id="div1">
<p id="p1">This is a paragraph.</p>
<p id="p2">This is another paragraph.</p>
</div>
let para = [Link]("p");
let node = [Link]("This is new.");
[Link](node);
let element = [Link]("#div1");
<div id="div1">
[Link](para); <p id="p1">This is a paragraph.</p>
<p id="p2">This is another paragraph.</p>
<p>This is new.</p>
</div>
82
HTML DOM

❖ Removing Existing HTML Elements


▪ To remove an HTML element, you must know the parent of the element
▪ Then you can use this syntax to remove the element you want:

83
HTML DOM

❖ <div id="div1">
<div id="div1">
<p id="p1">This is a paragraph.</p> <p id="p1">This is a paragraph.</p>
<p id="p2">This is another paragraph.</p>
<p id="p2">This is another paragraph.</p> </div>
</div>
let parent = [Link]("#div1");
let child = [Link]("#p1");
[Link](child);

84

You might also like