SE Web Chapter 4 JavaScriptv2
SE Web Chapter 4 JavaScriptv2
Jimma, Ethiopia.
Introduction to JavaScript
2
Cont...
3
Cont...
▪ A portion of the browser software that reads and executes JavaScript is an interpreter
▪ Web browsers
▪ Web servers
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...
❖ 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...
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.
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.
❖ 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
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
Variable declarations:
- Not required
- Data type not specified
Semi-colons are usually
not required, but always
allowed at statement end
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
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...
25
JavaScript keyword statements are very
similar to Java with small exceptions
26
Functions in JavaScript
❖ 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.
▪ 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...
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...
37
Cont...
Managing Events
▪ 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...
42
➢Example use: [Link]("I own a " + [Link]);
Three ways to create an object
❖ 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...
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...
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...
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...
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...
63
Form Processing and Validation
64
Cont...
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...
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
}
68
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
76
HTML DOM
❖ 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
• For example this JavaScript code changes the text inside the h1 element:
let header = [Link]("h1");
[Link] = "My new heading";
78
HTML DOM
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
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
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
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