Professional Documents
Culture Documents
Notes
Structure:
2.1 Java Script
2.1.1 JavaScript Functions and Events
2.1.2 External JavaScript
2.1.3 External JavaScript Advantages
2.1.4 JavaScript Display Possibilities
2.2 JavaScript Programs
2.3 JavaScript Operators
2.4 Programming Statements
2.5 JavaScript Functions
2.6 Handling Events
2.7 Working with Objects
2.8 Creating Frames and Windows
2.9 Processing Forms
2.10 JavaScript Forms
2.11 Summary
2.12 Check Your Progress
2.13 Questions and Exercises
2.14 Key Terms
2.15 Check Your Progress: Answers
2.16 Case Study
2.17 Further Readings
Objectives
After going through this unit, you should be able to know:
● JavaScript
● Operators and expressions
● Programming statements
● Event handling
● Frameset and windows
● HTML
● A Case Study based on this Unit
2.1 JavaScript
JavaScript is one of the three languages all web developers must learn:
JavaScript
JavaScript is the programming language of HTML and the Web.
Programming makes computers do what you want them to do.
JavaScript is easy to learn.
JavaScript can be placed in the <body> and the <head> sections of an HTML page.
The <script> Tag
In HTML, JavaScript code must be inserted between <script> and </script> tags.
Example
<script>
document.getElementById(“demo”).innerHTML = “My First JavaScript”;
</script>
Older examples may use a type attribute: <script type=“text/javascript”>. The type
attribute is not required. JavaScript is the default scripting language in HTML.
<body>
Notes
<h1>My Web Page</h1>
<p id=“demo”>A Paragraph</p>
<button type=“button” onclick=“myFunction()”>Try it</button>
</body>
</html>
JavaScript in <body>
In this example, a JavaScript function is placed in the <body> section of an HTML
page.
The function is invoked (called) when a button is clicked:
Example
<!DOCTYPE html>
<html>
<body>
<h1>My Web Page</h1>
<p id=“demo”>A Paragraph</p>
<button type=“button” onclick=“myFunction()”>Try it</button>
<script>
function myFunction() {
document.getElementById(“demo”).innerHTML = “Paragraph changed.”;
}
</script>
</body>
</html>
It is a good idea to place scripts at the bottom of the <body> element. This can
improve page load, because HTML display is not blocked by scripts loading.
Using window.alert()
You can use an alert box to display data:
Example
<!DOCTYPE html>
<html>
<body>
<h1>My First Web Page</h1>
<p>My first paragraph.</p>
<script>
window.alert(5 + 6);
</script>
</body>
</html>
Using document.write()
For testing purposes, it is convenient to use document.write():
Example
<!DOCTYPE html>
<html>
<body>
<h1>My First Web Page</h1>
<p>My first paragraph.</p>
<script>
document.write(5 + 6);
</script>
</body>
</html>
Using document.write() after an HTML document is fully loaded, will delete all
existing HTML:
Example
<!DOCTYPE html>
<html>
Notes
<body>
<h1>My First Web Page</h1>
<p>My first paragraph.</p>
<button onclick=“document.write(5 + 6)”>Try it</button>
</body>
</html>
The document.write() method should be used only for testing.
Using innerHTML
To access an HTML element, JavaScript can use the document.GetElement
ById(id) method.
The id attribute defines the HTML element. The innerHTML property defines the
HTML content:
Example
<!DOCTYPE html>
<html>
<body>
<h1>My First Web Page</h1>
<p>My First Paragraph</p>
<p id=“demo”></p>
<script>
document.getElementById(“demo”).innerHTML = 5 + 6;
</script>
</body>
</html>
To “display data” in HTML (in most cases), you will set the value of an innerHTML
property.
Using console.log()
In your browser, you can use the console.log() method to display data.
Activate the browser console with F12, and select “Console” in the menu.
Example
<!DOCTYPE html>
<html>
<body>
<h1>My First Web Page</h1>
<p>My first paragraph.</p>
<script>
console.log(5 + 6);
</script>
</body>
</html>
JavaScript syntax is the set of rules, how JavaScript programs are constructed.
JavaScript Statements
JavaScript statements are composed of:
Values, Operators, Expressions, Keywords, and Comments.
JavaScript Values
The JavaScript syntax defines two types of values: fixed values and variable values.
Fixed values are called literals. Variable values are called variables.
JavaScript Literals
The most important rules for writing fixed values are:
Numbers are written with or without decimals:
10.50
1001
Strings are text, written within double or single quotes:
“John Doe”
‘John Doe’
JavaScript Variables
In a programming language, variables are used to store data values.
JavaScript uses the var keyword to define variables.
An equal sign is used to assign values to variables.
In this example, x is defined as a variable. Then, x is assigned (given) the value 6:
var x;
x = 6;
JavaScript Operators
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 Comments
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 Identifiers
Identifiers are names.
In JavaScript, identifiers are used to name variables (and keywords, and functions,
and labels).
The rules for legal names are much the same in most programming languages.
In JavaScript, the first character must be a letter, an underscore (_), or a dollar sign ($).
Subsequent characters may be letters, digits, underscores, or dollar signs.
Numbers are not allowed as the first character. This way JavaScript can easily
distinguish identifiers from numbers.
JavaScript is Case-sensitive
All JavaScript identifiers are case-sensitive.
The variables lastName and lastname, are two different variables.
lastName = “Doe”;
lastname = “Peterson”;
JavaScript Statements
This statement tells the browser to write “Hello Dolly.” inside an HTML element with
id = “demo”.
Example
document.getElementById(“demo”).innerHTML = “Hello Dolly.”;
JavaScript Programs
Most JavaScript programs contain many JavaScript statements.
The statements are executed, one by one, in the same order as they are written.
In this example, x, y, and z is given values, and finally z is displayed:
Example
var x = 5;
var y = 6;
var z = x + y;
document.getElementById(“demo”).innerHTML = z;
JavaScript programs (and JavaScript statements) are often called JavaScript code.
Semicolons;
Semicolons separate JavaScript statements.
Add a semicolon at the end of each executable statement:
a = 5;
b = 6;
c = a + b;
When separated by semicolons, multiple statements on one line are allowed:
a = 5; b = 6; c = a + b;
On the web, you might see examples without semicolons.
Ending statements with semicolon is not required, but highly recommended.
JavaScript White Space
JavaScript ignores multiple spaces. You can add white space to your script to make
it more readable.
The following lines are equivalent:
var person = “Hege”;
var person=“Hege”;
A good practice is to put spaces around operators (= + - * /):
var x = y + z;
JavaScript Line Length and Line Breaks
For best readability, programmers often like to avoid code lines longer than
80 characters.
If a JavaScript statement does not fit on one line, the best place to break it, is after
Notes
an operator.
Example
document.getElementById(“demo”).innerHTML =
“Hello Dolly.”;
JavaScript Keywords
JavaScript statements often start with a keyword to identify the JavaScript action to
be performed.
Here is a list of some of the keywords you will learn about in this unit:
Keyword Description
break Terminates a switch or a loop
continue Jumps out of a loop and starts at the top
debugger Stops the execution of JavaScript, and calls (if available) the debugging function
do ... while Executes a block of statements, and repeats the block, while a condition is true
for Marks a block of statements to be executed, as long as a condition is true
function Declares a function
if ... else Marks a block of statements to be executed, depending on a condition
return Exits a function
switch Marks a block of statements to be executed, depending on different cases
try ... catch Implements error handling to a block of statements
var Declares a variable
Function Invocation
The code inside the function will execute when “something” invokes (calls) the
function:
● When an event occurs (when a user clicks a button)
● When it is invoked (called) from JavaScript code
● Automatically (self-invoked)
Function Return
When JavaScript reaches a return statement, the function will stop executing.
If the function was invoked from a statement, JavaScript will “return” to execute the
code after the invoking statement.
Functions often compute a return value. The return value is “returned” back to the
“caller”.
Example
Calculate the product of two numbers, and return the result:
var x = myFunction(4, 3); // Function is called, return value will end up in x
function myFunction(a, b) {
return a * b; // Function returns the product of a and b
}
The result in x will be:
12
Why Functions?
Notes
You can reuse code: Define the code once, and use it many times.
You can use the same code many times with different arguments, to produce
different results.
Example
Convert Fahrenheit to Celsius:
function toCelsius(fahrenheit) {
return (5/9) * (fahrenheit-32);
}
document.getElementById(“demo”).innerHTML = toCelsius(77);
The () Operator Invokes the Function
Using the example above, toCelsius refers to the function object, and toCelsius()
refers to the function result.
Example
Accessing a function without () will return the function definition:
function toCelsius(fahrenheit) {
return (5/9) * (fahrenheit-32);
}
document.getElementById(“demo”).innerHTML = toCelsius;
HTML Events
An HTML event can be something the browser does, or something a user does.
Here are some examples of HTML events:
● An HTML web page has finished loading.
● An HTML input field was changed.
● An HTML button was clicked.
Often, when events happen, you may want to do something.
JavaScript lets you execute code when events are detected.
HTML allows event handler attributes, with JavaScript code, to be added to HTML
elements.
All cars have the same properties, but the property values differ from car to car.
All cars have the same methods, but the methods are performed at different times.
JavaScript Objects
You have already learned that JavaScript variables are containers for data values.
This code assigns a simple value (Fiat) to a variable named car:
var car = “Fiat”;
Objects are variables too. But objects can contain many values.
This code assigns many values (Fiat, 500, white) to a variable named car:
var car = {type:“Fiat”, model:500, color:“white”};
The values are written as name:value pairs (name and value separated by a colon).
JavaScript objects are containers for named values.
Object Properties
The name:values pairs (in JavaScript objects) are called properties.
var person = {firstName:“John”, lastName:“Doe”, age:50, eyeColor:“blue”};
Property Property Value
firstName John
lastName Doe
age 50
eyeColor blue
Object Methods
Methods are actions that can be performed on objects.
Methods are stored in properties as function definitions.
Property Property Value
firstName John
lastName Doe
age 50
Object Definition
You define (and create) a JavaScript object with an object literal:
Example
var person = {firstName:“John”, lastName:“Doe”, age:50, eyeColor:“blue”};
Spaces and line breaks are not important. An object definition can span multiple
lines.
Example
var person = {
firstName:“John”,
lastName:“Doe”,
age:50,
eyeColor:“blue”
};
Accessing Object Properties
You can access object properties in two ways:
objectName.propertyName
or
objectName[“propertyName”]
Example 1
person.lastName;
Example 2
person[“lastName”];
Last name:
Note: The form itself is not visible. Also note that the default width of a text field is
20 characters.
Radio Button Input
<input type=“radio”> defines a radio button.
Radio buttons let a user select ONE of a limited number of choices.
Example
Notes
<form>
<input type=“radio” name=“sex” value=“male” checked>Male
<br>
<input type=“radio” name=“sex” value=“female”>Female
</form>
This is how the HTML code above will be displayed in a browser:
Male
Female
Last name:
Mouse
<br><br>
Notes
<input type=“submit” value=“Submit”>
</fieldset>
</form>
This is how the HTML code above will be displayed in a browser:
Top of Form
Personal information: First name:
Mickey
Last name:
Mouse
Bottom of Form
HTML Form Attributes
An HTML <form> element, with all possible attributes set, will look like this:
<form action=“action_page.php” method=“GET” target=“_blank” accept-charset=
“UTF-8” enctype=“application/x-www-form-urlencoded” autocomplete=“off” novalidate>
.
form elements
.
</form>
Here is the list of <form> attributes:
Attribute Description
accept-charset Specifies the charset used in the submitted form (default: the page charset)
action Specifies an address (url) where to submit the form (default: the submitting
page)
autocomplete Specifies if the browser should autocomplete the form (default: on)
enctype Specifies the encoding of the submitted data (default: is URL-encoded)
method Specifies the HTTP method used when submitting the form (default: GET)
name Specifies a name used to identify the form (for DOM usage:
document.forms.name)
novalidate Specifies that the browser should not validate the form
target Specifies the target of the address in the action attribute (default: _self)
JavaScript Example
function validateForm() {
var x = document.forms[“myForm”][“fname”].value;
if (x == null || x == “”) {
alert(“Name must be filled out”);
Amity Directorate of Distance and Online Education
54 Web-Enabled Business Processes
return false;
Notes
}
}
The function can be called when the form is submitted:
Data Validation
Data validation is the process of ensuring that computer input is clean, correct, and
useful.
Typical validation tasks are:
● has the user filled in all required fields?
● has the user entered a valid date?
● has the user entered text in a numeric field?
Most often, the purpose of data validation is to ensure correct input to a computer
application.
Validation can be defined by many different methods, and deployed in many
different ways.
Server-side validation is performed by a web server, after input has been sent to
the server.
Client-side validation is performed by a web browser, before input is sent to a web
server.
HTML Constraint Validation
HTML5 introduced a new HTML validation concept called constraint validation.
HTML constraint validation is based on:
● Constraint validation HTML Input Attributes
● Constraint validation CSS Pseudo Selectors
● Constraint validation DOM Properties and Methods
2.11 Summary
JavaScript is a cross-platform, object-oriented scripting language. It is a small and
lightweight language. Inside a host environment (for example, a web browser),
JavaScript can be connected to the objects of its environment to provide programmatic
control over them.
JavaScript contains a standard library of objects, such as Array, Date, and Math,
and a core set of language elements such as operators, control structures, and
statements. Core JavaScript can be extended for a variety of purposes by supplementing
it with additional objects; for example:
Ɣ Client-side JavaScript extends the core language by supplying objects to
control a browser and its Document Object Model (DOM). For example,
client-side extensions allow an application to place elements on an HTML form
and respond to user events such as mouse clicks, form input, and page
navigation.
Ɣ Server-side JavaScript extends the core language by supplying objects
relevant to running JavaScript on a server. For example, server-side
extensions allow an application to communicate with a database, provide
continuity of information from one invocation to another of the application, or
perform file manipulations on a server.
JavaScript works in all modern web browsers including Firefox, Netscape,
Opera, and Internet Explorer.
2.12 Check Your Progress
I. Fill in the Blanks
1. _________ method is used to remove focus from the specified object.
2. parseFloat(“FF2”)=_________.
3. JavaScript is a __________ typed language.
4. In JavaScript, RegExp Object Method test() is used to search a string and
returns __________
5. JavaScript RegExp Object has modifier ‘i’ to __________.
provide the HTML and CSS for the rewritten code. Here’s the HTML for both the side
Notes
menu and the main window:
<div id=“sidemenu”>
Home</br></br>
<a href=“about.htm”>About the Calculator</a></br></br>
<a href=“disclaimer.htm”>Disclaimer</a></br></br>
<a href=“relevant-reports.htm”>Relevant Reports</a></br></br>
<a href=‘mailto:webmaster@fscgroup.com’>Contact Us</a>
</div>
<div id=“mainwindow”>
<a href=“1”> Estimate Interruption Costs
</a></br> Estimate the cost per event, cost per average kW, cost per unserved kWh
and the total cost of unreliability.
</br></br>
<a href=“2”> Estimate Value of Reliability Improvement in a Static Environment
</a></br> Estimate the value associated with a given reliability improvement. The
environment is “static” because the expected reliability with and without the improvement
does not change over time.
</br></br>
<a href=“3”> Estimate Value of Reliability Improvement in a Dynamic Environment
</a></br> Estimates the value associated with a given reliability improvement.
The environment is “dynamic” because the expected reliability with and without the
improvement changes over time based on forecasts of SAIFI, SAIDI and CAIDI.
</div>
And the CSS for the side menu and the main window:
#sidemenu {
background-color: #ffffff;
-moz-border-radius: 15px;
-webkit-border-radius: 15px;
border: 4px solid #6495ed;
padding: 20px;
width: 160px;
height: 250px;
float: left;
text-align:left;
}
#mainwindow {
background-color: #ffffff;
-moz-border-radius: 15px;
-webkit-border-radius: 15px;
border: 4px solid #556b2f;
padding: 20px;
width: 630px;
TEXT BOOKS
1. Web Technology – N.P. Goplan and J. Akilandeswari
2. Internet Technology and Web Design – ISRD Group
3. HTML and Web Designing – Kris Jamsa and Konrad King
4. Ajax for Beginners – Ivon Bayross and Sharanam Shah
REFERENCES
1. Teach Yourself Web Technologies – Ivan Bayross – Reprinted 2011, Second
Edition
2. Web Technology – Ramesh Bangia – Reprint 2008
3. HTML for Beginners – Firuza Aibava – Second Edition
4. Internet and Web Design – Ramesh Bangia, Firewall Media
5. Web Design – Jenkins, Wiley India
6. HTML and Web Designing – Kris Jama and Konrad King, Tata McGraw Hill
Publishing Pvt. Ltd.
7. Using HTML 4, XML and Java 1.2 – Eric Ladd and Jin O’ Donwell, Prentice Hall
of India, New Delhi
8. Web Technology and Design – C. Xavier, New Age International Publishers
9. Java Server Pages – Ivan Bayross, Shroff Publishers & Distributors Pvt. Ltd,.
Delhi
10. Teach Yourself web Technologies – Ivon Bayross , BPB Publications – 2002
11. Web Programming – Chris Bates, Wiley – Dreamtech India Pvt. Ltd.