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

Chapter 3 (1)

Uploaded by

Getachew Abera
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
22 views

Chapter 3 (1)

Uploaded by

Getachew Abera
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 80

Internet Programming I

(CoSc3121)
Chapter 3
JavaScript

Prepared By: Helawe Behailu May, 2022


Content
• Introduction
• Introduction to JavaScript
• Variables, Expression,
Control Structure, Array
• JavaScript Functions
• Handling Events and
Exception Handling
• User Inputs: Form Processing
• Sessions and cookies using
JavaScript
Introduction
• What is Client-Side Scripting Language?
• Everything you see, click, and interact with on a website is the work of front-
end web development. Client-side frameworks and scripting languages like
JavaScript and AngularJS have made interactive websites possible.
• Here is a look at how this technology works in the scheme of a website, and
some of the most popular scripts and frameworks you should know.
Introduction (cont...)
Source:
Introduction (cont...)
• All websites run on three components: the server, the database, and
the client. The client is simply the browser a person is using to view a
site, and it’s where client-side technology is unpacked and processed.
• The server is at a remote location anywhere in the world—housing
data, running a site’s back-end architecture, processing requests, and
sending pages to the browser.
• The client is anywhere your users are viewing your site: mobile
devices, laptops, or desktop computers. Server-side scripting is
executed by a web server; client-side scripting is executed by a
browser.
Introduction (cont...)
• Client-end scripts are embedded in a website’s HTML markup code,
which is housed on the server in a language that’s compatible with, or
compiled to communicate with, the browser.
• The browser temporarily downloads that code, and then, apart from
the server, processes it. If it needs to request additional information
in response to user clicks, mouse-overs, etc. (called “events”), a
request is sent back to the server.
• Client-side scripting is always evolving—it’s growing simpler, more
nimble, and easier to use. As a result, sites are faster, more efficient,
and less work is left up to the server.
Introduction to JavaScript
• What is JavaScript?
• [Simply] JavaScript (often abbreviated as JS): is an object-oriented
computer programming language commonly used to create interactive
effects within web browsers.
Introduction to JavaScript (cont...)
• What is JavaScript? (cont...)
• JavaScript was initially created to “make web pages alive”.
• The programs in this language are called scripts. They can be written right in a
web page’s HTML and executed automatically as the page loads.
• Scripts are provided and executed as plain text. They don’t need special
preparation or compilation to run.
• In this aspect, JavaScript is very different from another language called Java.
• When JavaScript was created, it initially had another name: “LiveScript”. But
Java was very popular at that time, so it was decided that positioning a new
language as a “younger brother” of Java would help.
• But as it evolved, JavaScript became a fully independent language with its
own specification called ECMAScript, and now it has no relation to Java at all.
Introduction to JavaScript (cont...)
• What is JavaScript? (cont...)
• JavaScript: the first Web scripting language, developed by Netscape in 1995
syntactic similarities to Java/C++,
• but simpler & more flexible
• loose typing, dynamic variables, simple objects.
• An object-oriented scripting language that is designed primarily for people
who are building web pages using HTML.
• HTML to define the content of web pages
• CSS to specify the layout of web pages
• JavaScript to program the behavior of web pages
Introduction to JavaScript (cont...)
• JavaScript programs are embedded within HTML documents in source
code form which is interpreted by the browser.
• Platform independence
Recall:
• HTML is good for developing static pages.
• Can specify text/image layout, presentation, links.
• Web page looks the same each time it is accessed
• In order to develop interactive/reactive pages, we must integrate different programming
Introduction to JavaScript (cont...)
• Client-side programming:
• Programs can be written in a separate programming language
E.g., JavaScript, VBScript
• Programs are embedded in the HTML of a Web page, with tags to
identify the program component
e.g.
<script type="text/javascript">

</script>
• The browser executes the program as it loads the page, integrating the
dynamic output of the program with the static content of HTML
Introduction to JavaScript (cont...)
JavaScript can perform the following task:
• Decision making (switch and if statements)
• Used in input data validation
• Submitting forms(document.forms["myform"].submit();)
• Performing complex mathematical calculations.
• Adding dynamic features to Web pages
▪ Image rollovers
▪ Time-sensitive or random page elements
▪ Handling cookies (Cookies are data, stored in small text files, on your computer)
• Utilize buttons, text boxes, clickable images, prompts, frames
• Can Change HTML Content
• Can Change the value of HTML Attributes
• Can Change HTML styles for a given element
Introduction to JavaScript (cont...)
Limitations of client-side scripting
• Since script code is embedded in the page, viewable to the world
• For security reasons, scripts are limited in what they can do
e.g., can't access the client's hard drive
• Since designed to run on any machine platform, scripts do not contain
platform specific commands
• Script languages are not full-featured (didn’t support all features which is
supported by java)
Introduction to JavaScript (cont...)
Limitations of JavaScript
• JavaScript on a webpage may not read/write arbitrary files on the hard
disk, copy them or execute programs. It has no direct access to OS system
functions.
• Modern browsers allow it to work with files, but the access is limited and
only provided if the user does certain actions, like “dropping” a file into a
browser window or selecting it via an <input> tag.
• There are ways to interact with camera/microphone and other devices, but
they require a user’s explicit permission. So a JavaScript-enabled page may
not sneakily enable a web-camera, observe the surroundings and send the
information to the NSA. 👀
Introduction to JavaScript (cont...)
Limitations of JavaScript (cont...)
• Different tabs/windows generally do not know about each other.
Sometimes they do, for example when one window uses JavaScript to open
the other one. But even in this case, JavaScript from one page may not
access the other if they come from different sites (from a different domain,
protocol or port).
• This is called the “Same Origin Policy”. To work around that, both pages
must contain a special JavaScript code that handles data exchange.
• This limitation is, again, for the user’s safety. A page from
http://anysite.com which a user has opened must not be able to access
another browser tab with the URL http://gmail.com and steal information
from there.
Introduction to JavaScript (cont...)
JavaScript and Java
• Although the names resemble quite closely, they are different languages.
• Some facts:
• Both are object-oriented languages.
• JavaScript programs are interpreted in source code form.
• Java programs are first compiled into a device independent byte code format,
which is then interpreted.
• JavaScript is a small language and does not have many features that exist in
Java.
• Java is a powerful language and can be used in extremely sophisticated
applications.
Introduction to JavaScript (cont...)
• JavaScript code can be embedded in a Web page using SCRIPT tags
• the output of JavaScript code is displayed as if directly entered in HTML
• JavaScript can be placed in the <body> and the <head> sections of an
HTML page.
• In HTML, JavaScript code must be inserted between <script> and </script>
tags.
Introduction to JavaScript (cont...)
// Java script code inside the head part of our code
<head>
<script>
function myFunction() {
---
}
</script>
</head>
/ * Javascript code inside the body part of our html code */
// starts a single line comment
/*…*/ enclose multi-line comments
Introduction to JavaScript (cont...)
External JavaScript
• Scripts can also be placed in external files.
• External scripts are practical when the same code is used in many different
web pages.
• JavaScript files have the file extension .js
• To use an external script, put the name of the script file in the src (source)
attribute of the <script> tag:
<script src=“firstscript.js” type="text/javascript">
</script>
• Behaves exactly as if the contents of the specified JavaScript file appeared
directly between the tags
Introduction to JavaScript (cont...)
Advantages:
• Separation of HTML code from JavaScript code
• It makes HTML and JavaScript easier to read and maintain
• Less code has to be written, and stored.
• Commonly used JavaScript code can be shared among a number of
pages.
• Only a single copy needs to be stored on the web server.
• Such JavaScript files can be cached by the browser, thereby allowing
faster loading of the pages.
• The URL specified in the src attribute can refer to other web servers
also.
Introduction to JavaScript (cont...)
Introduction to JavaScript (cont...)
• JavaScript does not have any built-in print or display functions.
• JavaScript can "display" data in different ways:
• Writing into an alert box, using window.alert() or simply alert().
<script>
window.alert(“ Please fill the form!!”);
</script>
Introduction to JavaScript (cont...)
• Writing into the HTML output using document.write()
<script>
document.write(5 + 6);
</script>
• Writing into an HTML element, using innerHTML
<p id="demo"></p>
<script>
document.getElementById("demo").innerHTML =“Hello Javascript”;
</script>
• Writing into the browser console, using console.log()
<script>
console.log(5 + 6);
</script>
Introduction to JavaScript (cont...)
<html>
<head>
<title>JavaScript Page</title>
</head> Hello world!
<body>
How are
<script type="text/javascript">
// silly code to demonstrate output you?
document.write("Hello world!"); Here is some static text as well.
document.write("<p>How are <br />" +"<i>you</i>?</p>");
</script>
<p>Here is some static text as well. </p>
</body>
</html>
Introduction to JavaScript (cont...)
• JavaScript Syntax
• JavaScript syntax is the rules, how JavaScript programs are constructed.
• JavaScript statements are separated by semicolon (;)
var x = 5; var y = 6;
var z = x + y;
• JavaScript statements are composed of: Values, Operators,
Expressions, Keywords, and Comments.
• The JavaScript syntax defines two types of values: Fixed values and variable
values.
• Fixed values are called literals. Variable values are called variables.
• In HTML, JavaScript programs can be executed by the browser.
Introduction to JavaScript (cont...)
• JavaScript Syntax (cont...)
• JavaScript uses an assignment operator ( = ) to assign values to variables:
var x = 5;
var y = 6;
• JavaScript uses arithmetic operators ( + - * / ) to compute values:
(5 + 6) * 10
• JavaScript Keywords - are used to identify actions to be performed.
Example: The var keyword tells the browser to create a new variable:
var x = 5 + 6;
var y = x * 10;
• JavaScript uses the var keyword to define variables.
Introduction to JavaScript (cont...)
• JavaScript Syntax (cont...)
• Not all JavaScript statements are "executed".
• Code after double slashes // or between /* and */ is treated as a comment.
• Comments are ignored, and will not be executed:
var x = 5; // I will be executed
// var x = 6; I will NOT be executed
• JavaScript is Case Sensitive - all JavaScript identifiers are case sensitive.
• The variables lastName and lastname, are two different variables.
lastName = "Abel";
lastname = "Selam";
• JavaScript does not interpret VAR or Var as the keyword var.
Introduction to JavaScript (cont...)
• JavaScript Statements
• In HTML, JavaScript statements are "instructions" to be "executed" by the web
browser.
Example:
• document.getElementById("demo").innerHTML = "Hello Dolly.";
• This statement tells the browser to write "Hello Dolly." inside an HTML element with
id="demo":
• The statements are executed, one by one, in the same order as they are written.
Example:
var x = 5; var y = 6;
var z = x + y;
document.getElementById("demo").innerHTML = z;
• In this example, x, y, and z is given values, and finally z is displayed:
Introduction to JavaScript (cont...)
• JavaScript Statements (cont...)
• JavaScript statements are separated by semicolon.
Example:
var a = 5;
var b = 6;
• You can declare many variables in one statement - start the statement with var and separate
the variables by comma:
Example:
var person = "John Doe", carName = "Volvo";
• JavaScript ignores multiple spaces. You can add white space to your script to make it more
readable.
• If a JavaScript statement does not fit on one line, the best place to break it is before an
operator.
Example:
document.getElementById("demo").innerHTML
="Hello Dolly.";
JavaScript Variables
• JavaScript variables are containers for storing data values.
Example:
var x = 5;
var y = 6;
var z = x + y; /* In this example, x, y, and z, are variables */
• All JavaScript variables must be identified with unique names
called identifiers.
• Identifiers can be short names (like x and y), or more descriptive
names (age, sum, totalMark).
JavaScript Variables (cont...)
• The general rules for constructing names for variables (unique
identifiers) are:
• Names can contain letters, digits, underscores, and dollar signs.
• Names must begin with a letter , $ (dollar sign) or _(underscore)
• Names are case sensitive (y and Y are different variables)
• Reserved words (like JavaScript keywords) cannot be used as names
JavaScript Data Types
• In programming, data types is an important concept.
• To be able to operate on variables, it is important to know something about the
type.
• Without data types, a computer cannot safely solve this: var x = 16 + "Volvo"
• Does it make any sense to add "Volvo" to sixteen? Will produce an error or a
result?
• JavaScript has three primitive data types
• strings : "foo" 'howdy do' "I said 'hi’." ""
• numbers : 12 3.14159 1.5E6
• booleans : true false
• JavaScript variables can hold numbers like 100, and text values like “Hello JS".
JavaScript Data Types (cont...)
• In programming, text values are called text strings.
• Strings are written inside double or single quotes.
Example:
var carName = "Volvo XC60"; // Using double quotes
var carName = 'Volvo XC60'; // Using single quotes
• You can use quotes inside a string, as long as they don't match the quotes
surrounding the string:
Example:
var answer = "It's alright"; // Single quote inside double quotes
var answer = "He is called 'Johnny'"; // Single quotes inside double quotes
var answer = 'He is called "Johnny"'; // Double quotes inside single quotes
JavaScript Data Types (cont...)
• JavaScript has only one type of numbers which can be written with, or without decimals:
Example:
var x1 = 34.00; // Written with decimals
var x2 = 34; // Written without decimals
• Extra large or extra small numbers can be written with scientific (exponential) notation:
Example:
var y = 123e5; // 12300000
var z = 123e-5; // 0.00123
• JavaScript has dynamic types. This means that the same variable can be used as different types:
Example:
var x; // Now x is undefined
var x = 5; // Now x is a Number
var x = "John"; // Now x is a String
JavaScript Data Types (cont...)
• JavaScript Booleans have two values: true or false.
Example:
var x = true;
var y = false;
• Booleans are often used in conditional testing.
• JavaScript Arrays are written with square brackets in which the items are
separated by comma;
• The following code declares (creates) an array called cars, containing three items
(car names):
Example:
var cars = ["Saab", "Volvo", "BMW"];
JavaScript Data Types (cont...)
• JavaScript Objects are written with curly braces.
• Object properties are written as name:value pairs, separated by commas.
Example:
var person = {firstName:"John", lastName:"Doe", age:50,
eyeColor:"blue"};
• The object (person) in the example above has 4 properties: firstName,
lastName, age, and eyeColor.
JavaScript Data Types (cont...)
• In JavaScript we can use the JavaScript typeof
• Operator to find the type of a JavaScript variable:
Example:
typeof "John" // Returns string
typeof 3.14 // Returns number
typeof false // Returns boolean
typeof [1,2,3,4] // Returns object
typeof {name:'John', age:34} // Returns object
• In JavaScript, a variable without a value is undefined.
Example:
var person; // Value is undefined, typeof is also undefined
JavaScript Arithmetic Operators
• Arithmetic operators are used to perform arithmetic between variables and/or values.
• Example: Addition, Subtraction, Multiplication, Division, Modulus, Increment and
Decrement
• JavaScript Assignment operator are used to assign values to JavaScript variables.
Example:
<html>
<head> <title>Data Types and Variables</title></head>
<body>
<script type="text/javascript">
x = 1024;
document.write("<p>x = " + x + "</p>");
x = "foobar";
document.write("<p>x = " + x + "</p>");
</script>
</body>
</html>
JavaScript Function
• JavaScript function is a block of code (group of statements) designed to
perform a particular task.
• A JavaScript function is defined with the function keyword, followed by
a name, followed by parentheses ().
function function_name (parameters)
{
JavaScript commands
}
• parameters are the values sent to the function (note: not all functions require
parameters)
• { and } are used to mark the beginning and end of the commands in the
function.
Creating JavaScript Functions
• Function names are case-sensitive.
• Function names can contain letters, digits, underscores, and dollar signs.
• The function name must begin with a letter or underscore ( _ ) and cannot
contain any spaces.
• There is no limit to the number of function parameters that a function may
contain.
• The parentheses may include parameter names separated by
commas: (parameter1, parameter2, ...)
• The code to be executed, by the function, is placed inside curly brackets: {}
• Function arguments are the real values received by the function when it is
invoked
Performing an Action with a Function
• Function Definition
function ShowDate(date) {
document.write(“Today is” + date + “<br>”);
}
Function Call:
• The code inside the function will execute when "something" invokes the function:
• When an event occurs (eg. when a user clicks a button), called from JavaScript
code or self-invoking.
• If a function is called with missing arguments (less than declared), the missing
values are set to: undefined.
• var Today = date(); // Variable declaraion
• ShowDate(Today); // function call with arguments
Function Return
• When JavaScript reaches a return statement, the function will stop
executing and if the function invoked from a statement, it will "return" to
execute the code after the caller statement.
• The return value of a function is "returned" back to the "caller":
Example:
function Area(Width, Length)
{
var Size = Width*Length; // calculate the area and assigned it size
return Size; // return the result to its caller statement
}
• var area= Area (4, 3); // function is called, return value will end up in area
Placing a Function in an HTML File
• The function definition must be placed before the command that calls
the function.
• One convention is to place all of the function definitions in the
<head> section.
• A function is executed only when called by another JavaScript
command.
• It’s common practice for JavaScript programmers to create libraries of
functions located in external files.
Working with Conditional Statements
• Comparison, Logical and Conditional Operators
To create a condition, you need one of the three types of operators:
• A comparison operator compares the value of one element with that of
another, which creates a Boolean expression that is either true or false.
• A logical operator connects two or more Boolean expressions.
• A conditional operator tests whether a specific condition is true and returns
one value if the condition is true and a different value if the condition is false.
Working with Conditional Statements (cont...)
• An Example of Boolean Expressions
• x < 100;
• if x is less than 100, this expression returns the value true; however, if x is 100
or greater, the expression is false
• y == 20;
• the y variable must have an exact value of 20 for the expression to be true
• comparison operator uses a double equal sign (==)
Working with Conditional Statements (cont...)
• Comparison Operators
Working with Conditional Statements (cont...)
• A Logical Operator
• The logical operator && returns a value of true only if all of the Boolean
expressions are true.
Working with Conditional Statements (cont...)
• A Conditional Operator
• Conditional operator tests whether a specific condition is true and returns
one value if the condition is true and a different value if the condition is false.
Syntax:
variable_name = (condition) ? value1:value2;
Example:
message = (mail == “Yes”) ? “You have mail”:“No mail”;
• Tests whether the mail variable is equal to the value “Yes”
• if it is, the Message variable has the value “You have mail”;
• otherwise, the Message variable has the value “No mail”.
JavaScript if Statement
• Use if statement to execute some code only if a specified condition is true
• Syntax:
if (condition)
{
JavaScript Commands
}
• condition is an expression that is either true or false
• If the condition is true, the JavaScript Commands in the command block
are executed
• If the condition is not true, then no action is taken
JavaScript if Statement (cont...)
Example:
<html><body>
<p>This example demonstrates the If statement.</p>
<script type="text/javascript">
var d = new Date();
var time = d.getHours();
if (time < 10)
{
document.write("<b>Good morning</b>");
}
</script>
<p>If the time on your browser is less than 10, you will get a "Good morning" greeting. </p>
</body>
</html>
JavaScript if-else Statement
• Use if….else statement to execute some code if a condition is true and
another code if the condition is false.
• Syntax:
if (condition) {
block of code to be executed if the condition is true
}
else {
block of code to be executed if the condition is false
}
• If the condition is true, the JavaScript Commands in the command block
are executed.
• If the condition is not true, then else part will be executed.
JavaScript if-else Statement (cont...)
Example 1:
<html><body>
<p>This example demonstrates the If…else statement.</p>
<script type="text/javascript">
var d = new Date();
var time = d.getHours();
if (time < 10){
document.write("<b>Good morning</b>");}
else{
document.write("<b>Good Afternoon</b>");}
</script>
<p>If the time on your browser is less than 10, you will get a "Good morning" greeting.
Otherwise you will get a "Good Afternoon" greeting</p>
</body></html>
JavaScript if-else Statement (cont...)
Example 2:
<html><body>
<p>Christmas wish and date calculator</p>
<script type="text/javascript">
var d = new Date(); var time = d.getHours();
var thisMonth= d.getMonth();
var thisDay = d.getDate();
var thisYear =d.getFullYear();
document.write("Today is " + thisMonth + "/"+thisDay+"/"+thisYear+"<br />");
daysLeft =37-thisday;
if (daysLeft > 0) {
document.write("Only "+daysLeft+" days are left until Christmas");
} else {
document.write("Happy Holidays"); }
</script></body></html>
JavaScript if..., else if..., else Statement
• Use the if....else if...else statement to select one of several blocks of code to be executed.
Syntax:
if (condition1) {
block of code to be executed if condition1 is true
} else if (condition2) {
block of code to be executed if the condition1 is false and condition2 is true
}
…..
else {
block of code to be executed if the condition1 is false and condition2 is false
}
// If condition1 is true then the 1st block of code will be executed.
// If condition1 is false and condition2 is true then the 2nd block of code will be executed,
otherwise the 3rd block of code will be executed.
JavaScript if..., else if..., else Statement (cont...)
Example:
<html><body>
<script type="text/javascript">
var d = new Date();
var time = d.getHours();
if (time<10)
document.write("<b>Good morning</b>");
else if (time>=10 && time<16)
document.write("<b>Good Afternoon</b>");
else
document.write("<b>Hello World!</b>");
</script>
<p>This example demonstrates the if..else if...else statement.</p>
</body></html>
JavaScript Switch Statement
• The switch statement is used to perform different action based on different conditions
• Use the switch statement to select one of many blocks of code to be executed.
switch(expression) {
case n:
code block
break;
case n:
code block
break;
default:
default code block
}
• 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.
JavaScript Switch Statement (cont...)
Example:
switch (new Date().getDay()) {
case 0:
day = "Sunday";
break;
case 1:
day = "Monday";
break;
case 2:
day = "Tuesday";
break;
case 3:
day = "Wednesday";
break;
case 4:
day = "Thursday";
break;
case 5:
day = "Friday";
break;
case 6:
day = "Saturday";
break;
}
The for Loop
• The For loop allows you to create a group of commands to be executed a number of times
through the use of a counter that tracks the number of times the command block has been run.
• Syntax:
for (start; condition; update){
JavaScript Commands
}
• Start is the starting value of the counter.
• Condition is a Boolean expression that must be true for the loop to continue.
• Update specifies how the counter changes in value each time the command block is executed.
• Set an initial value for the counter, and each time the command block is executed, the counter
changes in value.
• When the counter reaches a value above or below a certain stopping value, the loop ends.
The for Loop (cont...)
• Example:
<html>
<body>
<script type="text/javascript">
for (i = 1; i <= 6; i++){
document.write("<h" + i + ">This is heading " + i);
document.write("</h" + i + ">");
}
</script>
</body>
</html>
The for Loop (cont...)
• Example 2:
<html>
<body>
<p id="demo"></p>
<script>
var cars = ["BMW", "Volvo", "Saab", "Ford"];
text = "";
for (var i = 0; i < cars.length; i++) {
text += cars[i] + "<br>";
}
document.getElementById("demo").innerHTML = text;
</script>
</body>
</html>
The for Loop (cont...)
• Example 3:
<html><body>
<table border="1px">
<tr>
<script>
for(var num=1; num<=5; num++){
document.write("<td>"+ num +"</td>");
}
</script>
</tr>
</table>
</body></html>
The for Loop (cont...)
• Example 4: (nested for)
<html>
<body><table border="1px"><tr>
<script>
var rownum, colnum;
for(rownum=1; rownum<=3; rownum++){
document.write("<tr>");
for(colnum=1; colnum<=4; colnum++){
document.write("<td>"+ rownum + "," + colnum +"</td>");
}
document.write("</tr>");
}
</script></tr></table></body>
</html>
The for Loop (cont...)
• Example 5: (for in loop)
<html>
<body><p id="demo"></p>
<script>
var txt = ""; var x;
var person = {fname:"Sam", lname:"Abebe", age:25};
for (x in person) {
txt += person[x] + " ";
}
document.getElementById("demo").innerHTML = txt;
</script>
</body> </html>
The while Loop
• The While loop runs a command group as long as a specific condition is
met, but it does not employ any counters.
• Loops through a block of code a specified number of times or while a
specified condition is true.
• The general syntax of the While loop is:
while (condition)
{
JavaScript Commands
}
• condition is a Boolean expression that can be either true or false
The while Loop (cont...)
Example 1:
<html>
<body>
<table border="1px">
<tr>
<script>
var num=1;
while(num<=5){
document.write("<td>"+ num +"</td>");
num++;
}
</script></tr>
</table></body>
</html>
The while Loop (cont...)
Example 2:
<html><body>
<table border="1px"> <tr><script>
var rownum=1, colnum=1;
while(rownum<=3) {
document.write("<tr>");
while(colnum<=4){
document.write("<td>"+ rownum + "," + colnum +"</td>");
colnum++;
}
document.write("</tr>");
rownum++; colnum=1;
}</script></tr></table>
</body></html>
Using Arrays
• JavaScript arrays are used to store multiple values in a single variable(an ordered
collection of values referenced by a single variable name).
• Syntax:
Using the JavaScript new keyword
var array-name = new Array(size);
• Size is the number of elements in the array (optional)
• To assign value to array elements, use:
array-name[i] = value;
Where i is the index of the array item. The 1st item has an index value of 0.
Or
Using array literal(easiest and fast way)
• var array-name = [item1, item2, ...];
Using Arrays (cont...)
Example 1:
<html><head><title> Javascript array</title>
</head><body><script>
var fruits= new Array();
fruits[0]="Apple"; fruits[1]="Mango"; fruits[2]="Orange";
document.write("<h3>"+" The fruits I like most:"+"</h3>");
document.write("<ul>");
for (var i = 0; i < fruits.length; i++) {
document.write("<li>"+fruits[i] + "</li>");
}
document.write("</ul>");
</script>
</body></html>
Array declaration and assignment within one line
<body>
<script>
var MonthTxt = ["January", "February", "March", "April", "May","June", "July", "August",
"September", "October", "November", "December“];
document.write("<h3>"+" Months of the year are:"+"</h3>");
document.write("<ul>");
for (var i = 0; i < MonthTxt.length; i++) {
document.write("<li>"+MonthTxt[i] + "</li>");
}
document.write("</ul>");
</script>
</body>
// we can use array() or array[] in array declaration and assignment
JavaScript Objects and Methods
• In the context of JavaScript:
• An object is a collection of properties and methods which can be viewed, modified and
interacted with.
• A simple example of property is color, which is rather easy to visualize.
• They can be directly manipulated by referring to the object and the property by name
and then setting its value.
• For example, the background color of a page can be changed as:
document.bgcolor = “blue”;
• In the object-oriented paradigm, methods refer to functions that can be used to
manipulate objects and their properties.
• Example:
The method write(), which when invoked on the document object, causes a specific string
of characters to be outputted.
document.write (“Hello Good Day”);
JavaScript Objects and Methods (cont...)
• Methods which are defined on an object give the range of choices available for
interacting with the object.
• Some examples:
• A window object can be opened or closed using the open() and close() methods respectively.
• A form object has a submit() method which transmits the contents of the form to the web
server.
• The sequential list of a user’s path through a number of URLs is represented by the
history object, which has forward() and backward() methods to move through the list.
• Apart from the pre-defined methods, it is also possible to create user-defined methods.
• Control the rate with which a line of text scrolls across the screen.
• Determine the path of an animated object across the display.
Data Validation
• JavaScript can be used for client-side validation of data entered in HTML forms.
• Data entered can be extracted and accessed.
• Checks can be made on the data entered.
• Non-alphabetic characters in name.
• Non-numeric characters in roll number, age, etc.
• Bid amount less than minimum permissible.
• A data validation example:
• A student registration form.
• A function checks whether the roll number is a 7-digit numeric value.
• Invoked when the form is submitted.
• Check performed before form data are transmitted to server-side application.
Simple Animation
• JavaScript provides following two functions to be frequently used in
animation programs.
• setTimeout( function, duration)
• Schedules a piece of Javascript code to run at some specified time in the future.
• Time specified in milliseconds.
• Commonly used to perform animation or other kinds of repetitive operations.
• setInterval(function, duration) - This function calls function after
every duration of milliseconds.
• clearTimeout(setTimeout_variable) - This function calls clears any timer set
by the setTimeout() functions.
Simple Animation (cont...)
Example 1:
<html><head>
<script type="text/javascript">
var imgObj = null;
function init(){
imgObj = document.getElementById('myImage');
imgObj.style.position = 'relative';
imgObj.style.left = '0px';
}
function moveRight(){
imgObj.style.left = parseInt(imgObj.style.left) + 10 + 'px';
}
Simple Animation (cont...)
Example 1 (cont...):
</script>
</head>
<body onload="init(); setInterval(moveRight,200);">
<form>
<img id="myImage" src="1.jpg"/>
</form>
</body>
</html>
History Back / Forward
• Use the history object.
• Call the back() and forward() methods to scroll through the recently visited
pages.
• history.back() - same as clicking back in the browser.
• history.forward() - same as clicking forward in the browser.
Example:
• <button onclick="window.history.back()"> Go Back </button>
• <button onclick="window.history.forward()"> Go forward </button>
Page Redirection
• Commonly used feature.
• A previously existing web site might have moved to a new location.
• You may want the request to be redirected to a site depending on the browser type and
version.
• Manipulate the window.location attribute.
• An example follows.
• Will take us to a page after 5 seconds.

Example:
<script>
function getgoing (){
window.location = "http://www.bdu.edu.et";
}
alert( "You will be redirected in five seconds.");
setTimeout ('getgoing()', 5000);
</script >
Creating New Browser Window
• To open a new window, we need to call the window.open() method.
• window.open (‘url to open’, ‘window name’, attribute1, attribute2, …);
• Window attributes:
• width = 300
• height = 200
• resizable = yes or no
• scrollbars = yes or no
• toolbars = yes or no
• status = yes or no
• menubar = yes or no
• copyhistory = yes or no
• An example is shown with some of the attributes.
Creating New Browser Window (cont...)
Example:
<FORM>
<INPUT type="button" value="New Window!" onClick="window.open('http://www.bdu.edu.et’,
'mywindow’, 'width=400', 'height=200', 'toolbar=yes', 'status=yes')">
</FORM>
END

You might also like