6 Cse - Cs8651 Ip Unit 2
6 Cse - Cs8651 Ip Unit 2
proceeding:
This document is confidential and intended solely for the educational purpose of
RMK Group of Educational Institutions. If you have received this document
through email in error, please notify the system manager. This document contains
proprietary information and is intended only to the respective group / learning
community as intended. If you are not the addressee you should not disseminate,
distribute or copy through e-mail. Please notify the sender immediately by e-mail
if you have received this document by mistake and delete this document from
your system. If you are not the intended recipient you are notified that disclosing,
copying, distributing or taking any action in reliance on the contents of this
information is strictly prohibited.
CS8651
Internet Programming
Department : CSE
Batch/Year : 2018 -22 / III
Created by : A. JASMINE GILDA,
Assistant Professor.
TABLE OF CONTENTS
S. No. Topic
1 Course Objectives
2 Pre-Requisites
3 Syllabus
4 Course outcomes
6 Lecture Plan
8 Lecture Notes
9 Assignments
10 Online Certifications
11 Assessment Schedule
5
COURSE OBJECTIVE
7
SYLLABUS
C PO PO PO PO PO PO PO PO PO PO PO PO PSO PS PSO
O 1 2 3 4 5 6 7 8 9 10 11 12 1 O2 3
1 3 3 3 - 3 - - - 2 - - - 3 3 3
2 3 3 3 - 3 - - - 2 - - 3 3 3 3
3 3 3 3 - 3 - - - 2 - - 3 3 3 3
4 3 3 3 - 3 - - - 2 - - 3 3 3 3
5 3 3 3 - 3 - - - 2 - - 3 3 3 3
6 3 3 3 - 3 - - - 2 - - 3 3 3 3
LECTURE PLAN – UNIT II
Session Mode of
Topics to be covered Reference
No. delivery
9 SQL PPT 1
1. Deitel and Deitel and Nieto, ―Internet and World Wide Web - How to
WEBSITE DEVELOPMENT
INTRODUCTION
Javascript is a dynamic computer programming language. It is lightweight and most
commonly used as a part of web pages, whose implementations allow client-side script
to interact with the user and make dynamic pages. It is an interpreted programming
language with object-oriented capabilities.
JavaScript was first known as LiveScript, but Netscape changed its name to JavaScript,
possibly because of the excitement being generated by Java. JavaScript made its first
appearance in Netscape 2.0 in 1995 with the name LiveScript. The general-purpose
core of the language has been embedded in Netscape, Internet Explorer, and other
web browsers.
The ECMA-262 Specification defined a standard version of the core JavaScript
language.
• JavaScript is a lightweight, interpreted programming language.
• Designed for creating network-centric applications.
• Complementary to and integrated with Java.
• Complementary to and integrated with HTML.
• Open and cross-platform
Client-side JavaScript
• Client-side JavaScript is the most common form of the language. The script should
be included in or referenced by an HTML document for the code to be interpreted by
the browser.
• It means that a web page need not be a static HTML, but can include programs that
interact with the user, control the browser, and dynamically create HTML content.
• The JavaScript client-side mechanism provides many advantages over traditional CGI
server-side scripts. For example, you might use JavaScript to check if the user has
entered a valid e-mail address in a form field.
• The JavaScript code is executed when the user submits the form, and only if all the
entries are valid, they would be submitted to the Web Server.
• JavaScript can be used to trap user-initiated events such as button clicks, link
navigation, and other actions that the user initiates explicitly or implicitly.
Advantages of JavaScript
Less server interaction − You can validate user input before sending the page off
to the server. This saves server traffic, which means less load on your server.
Immediate feedback to the visitors − They don't have to wait for a page reload
to see if they have forgotten to enter something.
Increased interactivity − You can create interfaces that react when the user
hovers over them with a mouse or activates them via the keyboard.
Richer interfaces − You can use JavaScript to include such items as drag-and-drop
components and sliders to give a Rich Interface to your site visitors.
Limitations of JavaScript
Client-side JavaScript does not allow the reading or writing of files. This has been
kept for security reason.
JavaScript cannot be used for networking applications because there is no such
support available.
JavaScript doesn't have any multithreading or multiprocessor capabilities.
JavaScript can be implemented using JavaScript statements that are placed within
the<script>... </script> HTML tags in a web page.
You can place the <script> tags, containing your JavaScript, anywhere within you web
page, but it is normally recommended that you should keep it within the <head> tags.
The <script> tag alerts the browser program to start interpreting all the text between
these tags as a script. A simple syntax of your JavaScript will appear as follows.
The script tag takes two important attributes –
• Language − This attribute specifies what scripting language you are using. Typically,
its value will be javascript. Although recent versions of HTML (and XHTML, its
successor) have phased out the use of this attribute.
• Type − This attribute is what is now recommended to indicate the scripting language
in use and its value should be set to "text/javascript".
<script>
document.getElementById("demo").innerHTML = 5 + 6;
</script>
</body>
</html>
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>
<script>
console.log(5 + 6);
</script>
</body>
</html>
SYNTAX OF JAVASCRIPT
JavaScript syntax is the set of rules, how JavaScript programs are constructed.
A computer program is a list of "instructions" to be "executed" by the computer.
In a programming language, these program instructions are called statements. JavaScript is a programming
language.
JavaScript statements are separated by semicolons.
var x = 5;
var y = 6;
var z = x + y;
Statements
JavaScript statements are composed of:
Values, Operators, Expressions, Keywords, and Comments.
Values
The JavaScript syntax defines two types of values: Fixed values and variable values.
Fixed values are called literals. Variable values are called variables.
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;
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
Expressions
An expression is a combination of values, variables, and operators, which computes to a value.
The computation is called an evaluation.
For example, 5 * 10 evaluates to 50:
5 * 10
Expressions can also contain variable values:
x * 10
The values can be of various types, such as numbers and strings.
For example, "John" + " " + "Doe", evaluates to "John Doe":
"John" + " " + "Doe"
Keywords
Keywords are used to identify actions to be performed. The var keyword tells the browser to create a new
variable:
var x = 5 + 6;
var y = x * 10;
Comments in JavaScript
JavaScript supports both C-style and C++-style comments, Thus −
• Any text between a // and the end of a line is treated as a comment and is ignored by JavaScript.
• Any text between the characters /* and */ is treated as a comment. This may span multiple lines.
• JavaScript also recognizes the HTML comment opening sequence <!--. JavaScript treats this as a single-
line comment, just as it does the // comment.
• The HTML comment closing sequence --> is not recognized by JavaScript so it should be written as // - >
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.
FUNCTIONS
• A function is a block of code designed to perform a particular task.
• A function is a group of reusable code which can be called anywhere in your program. This eliminates the
need of writing the same code again and again. It helps programmers in writing modular codes.
Functions allow a programmer to divide a big program into a number of small and manageable functions.
• A JavaScript function is executed when "something" invokes it (calls it).
Syntax
A JavaScript function is defined with the function keyword, followed by a name, followed by parentheses ().
function name(parameter1, parameter2, parameter3) {
code to be executed
}
Function parameters are the names listed in the function definition. Function arguments are the real values
received by the function when it is invoked. Inside the function, the arguments are used as local variables.
function myFunction(p1, p2) {
return p1 * p2; // The function returns the product of p1 and p2
}
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)
<html> <head>
<script type="text/javascript">
function sayHello(name, age)
{
document.write (name + " is " + age + " years old.");
}
</script>
</head>
<body>
<p>Click the following button to call the function</p>
<form>
<input type="button" onclick="sayHello('Zara', 7)" value="Say Hello">
</form>
<p>Use different parameters inside the function and then try...</p>
</body>
</html>
return Statement
A JavaScript function can have an optional return statement. This is required if you want to return a value
from a function. This statement should be the last statement in a function.
<html>
<head>
<script type="text/javascript">
function concatenate(first, last)
{
var full;
full = first + last;
return full;
}
function secondFunction()
{
var result;
result = concatenate('Zara', 'Ali');
document.write (result );
}
</script>
</head>
<body>
<p>Click the following button to call the function</p>
<form>
<input type="button" onclick="secondFunction()" value="Call Function">
<form>
</body>
</html>
Nested Functions
Function inside another function is known as Nested Functions.
<html>
<head>
<script type="text/javascript">
<!--
function hypotenuse(a, b) {
function square(x) { return x*x; }
return Math.sqrt(square(a) + square(b));
}
function secondFunction(){
var result;
result = hypotenuse(1,2);
document.write ( result );
}
//-->
</script>
</head>
<body>
<form>
<input type="button" onclick="secondFunction()" value="Call Function">
</form>
</body>
</html>
Function Constructors
The function statement is not the only way to define a new function; you can define your function
dynamically using Function() constructor along with the new operator.
Note − Constructor is a terminology from Object Oriented Programming. You may not feel comfortable for
the first time, which is OK.
Syntax
Following is the syntax to create a function using Function( ) constructor along with the new operator.
<script type="text/javascript">
var variablename = new Function(Arg1, Arg2..., "Function Body");
</script>
The Function() constructor expects any number of string arguments. The last argument is the body of the
function – it can contain arbitrary JavaScript statements, separated from each other by semicolons.
Notice that the Function() constructor is not passed any argument that specifies a name for the function it
creates. The unnamed functions created with the Function() constructor are called anonymous functions.
<html>
<head>
<script type="text/javascript">
<!--
var func = new Function("x", "y", "return x*y;");
function secondFunction(){
var result;
result = func(10,20);
document.write ( result );
}
//-->
</script>
</head>
<body>
<form>
<input type="button" onclick="secondFunction()" value="Call Function">
</form> </body> </html>
Function literals
Function literals which is another new way of defining functions. A function literal is an expression that
defines an unnamed function.
Syntax
The syntax for a function literal is much like a function statement, except that it is used as an expression
rather than a statement and no function name is required.
<script type="text/javascript">
var variablename = function(Argument List){
Function Body
};
</script>
Syntactically, you can specify a function name while creating a literal function as follows.
<script type="text/javascript">
var variablename = function FunctionName(Argument List){
Function Body
};
</script>
But this name does not have any significance, so it is not worthwhile.
<html>
<head>
<script type="text/javascript">
var func = function(x,y){ return x*y };
function secondFunction(){
var result;
result = func(10,20);
document.write ( result );
}
</script>
</head>
<body>
<p>Click the following button to call the function</p>
<form>
<input type="button" onclick="secondFunction()" value="Call Function">
</form>
</body></html>
OBJECTS
Objects are composed of attributes. If an attribute contains a function, it is considered to be a method of
the object, otherwise the attribute is considered a property.
In real life, a car is an object.
A car has properties like weight and color, and methods like start and stop:
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.
var car = "Fiat";
Objects are variables too. But objects can contain many values.
var car = {type:"Fiat", model:500, color:"white"};
Properties
The name:values pairs (in JavaScript objects) are called properties.
var person = {firstName:"Kalpana", lastName:"Vijayaraghavan", age:32};
Example
<!DOCTYPE html><html>
<body>
<p id="demo"></p>
<script>
var person = {firstName:"Kalpana", lastName:"Vijayaraghavan", age:32};
document.getElementById("demo").innerHTML =
person.firstName + " is " + person.age + " years old.";
</script>
</body></html>
User-Defined Objects
All user-defined objects and built-in objects are descendants of an object called Object.
Example 2:
<html> <head>
<title>User-defined objects</title> OUTPUT:
<script type="text/javascript">
// Define a function which will work as a method
function addPrice(amount){
this.price = amount;
OUTPUT:
}
function book(title, author){ Book name is : C++
NUMBER OBJECT
The Number object represents numerical date, either integers or floating-point numbers. In general, you
do not need to worry about Number objects because the browser automatically converts number literals
to instances of the number class.
Syntax
The syntax for creating a number object is as follows −
var val = new Number(number);
In the place of number, if you provide any non-number argument, then the argument cannot be
converted into a number, it returns NaN (Not-a-Number).
Converting Variables to Numbers
There are 3 JavaScript functions that can be used to convert variables to numbers:
• The Number() method
• The parseInt() method
• The parseFloat() method
These methods are not number methods, but global JavaScript methods.
The parseInt() Method - parses a string and returns a whole number. Spaces are allowed. Only the
first number is returned:
parseInt("10"); // returns 10
parseInt("10.33"); // returns 10
parseInt("10 20 30"); // returns 10
parseInt("10 years"); // returns 10
parseInt("years 10"); // returns NaN
The parseFloat() Method - parses a string and returns a number. Spaces are allowed. Only the first
number is returned:
parseFloat("10"); // returns 10
parseFloat("10.33"); // returns 10.33
parseFloat("10 20 30"); // returns 10
parseFloat("10 years"); // returns 10
parseFloat("years 10"); // returns NaN
The valueOf() Method - returns a number as a number.
var x = 123;
x.valueOf(); // returns 123 from variable x
(123).valueOf(); // returns 123 from literal 123
(100 + 23).valueOf(); // returns 123 from expression 100 + 23
Global Methods
JavaScript global functions can be used on all JavaScript data types.
Global Methods
JavaScript global functions can be used on all JavaScript data types.
These are the most relevant methods, when working with numbers:
Method Description
Number Methods
JavaScript number methods are methods that can be used on numbers:
Method Description
BOOLEAN OBJECT
The Boolean object represents two values, either "true" or "false". If value parameter is omitted or is 0, -
0, null, false, NaN, undefined, or the empty string (""), the object has an initial value of false.
Syntax
Use the following syntax to create a boolean object.
var val = new Boolean(value);
Method Description
toSource() Returns a string containing the source of the Boolean object; you
can use this string to create an equivalent object.
<!DOCTYPE html>
<html><body>
<button onclick="myFunction()">Check</button>
<p id="demo"></p>
<script>
function myFunction()
{
document.getElementById("demo").innerHTML = Boolean(10 > 9);
}
</script>
</body></html>
ARRAY OBJECT
The Array object lets you store multiple values in a single variable. It stores a fixed-size sequential
collection of elements of the same type. An array is used to store a collection of data, but it is often more
useful to think of an array as a collection of variables of the same type.
Syntax
var fruits = new Array( "apple", "orange", "mango" );
OR
var fruits = [ "apple", "orange", "mango" ]; //easiest method - literal
You will use ordinal numbers to access and to set values inside an array as follows.
fruits[0] is the first element
fruits[1] is the second element
fruits[2] is the third element
Method Description
concat() Joins two or more arrays, and returns a copy of the joined arrays
indexOf() Search the array for an element and returns its position
lastIndexOf() Search the array for an element, starting at the end, and returns
its position
pop() Removes the last element of an array, and returns that element
push() Adds new elements to the end of an array, and returns the new
length
shift() Removes the first element of an array, and returns that element
unshift() Adds new elements to the beginning of an array, and returns the
new length
Example:
<!DOCTYPE html><html>
<body>
<button onclick="myNumber()">Sorting of Numbers</button>
<p id="demo"></p>
<p id="demo1"></p>
<button onclick="myFruits()">Sorting of Alphabets</button>
<p id="demo2"></p>
<button onclick="myList()">Listing Fruits</button>
<p id="demo3"></p>
<script>
function myFruits() {
var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.push("Lemon"); //to add an element to the array
fruits[fruits.length] = "Pomegranate"
fruits[6]="Grapes"
document.getElementById("demo2").innerHTML = fruits;
fruits.sort();
fruits.reverse();
document.getElementById("demo2").innerHTML = fruits;
}
function myNumber() {
var points = [40, 100, 1, 5, 25, 10];
points.sort(function(a, b){return a-b});
document.getElementById("demo").innerHTML = points;
points.sort(function(a, b){return b-a});
document.getElementById("demo1").innerHTML = points;
}
function myList()
{
var index;
var text = "<ul>";
var fruits = ["Banana", "Orange", "Apple", "Mango"];
for (index = 0; index < fruits.length; index++) {
text += "<li>" + fruits[index] + "</li>";
}
text += "</ul>";
document.getElementById("demo3").innerHTML = text;
}
</script>
</body>
</html>
<script>
function myFruits() {
var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.push("Lemon"); //to add an element to the array
fruits[fruits.length] = "Pomegranate"
fruits[6]="Grapes"
document.getElementById("demo2").innerHTML = fruits;
fruits.sort();
fruits.reverse();
document.getElementById("demo2").innerHTML = fruits;
}
function myNumber() {
var points = [40, 100, 1, 5, 25, 10];
points.sort(function(a, b){return a-b});
document.getElementById("demo").innerHTML = points;
points.sort(function(a, b){return b-a});
document.getElementById("demo1").innerHTML = points;
}
function myList()
{
var index;
var text = "<ul>";
var fruits = ["Banana", "Orange", "Apple", "Mango"];
for (index = 0; index < fruits.length; index++) {
text += "<li>" + fruits[index] + "</li>";
}
text += "</ul>";
document.getElementById("demo3").innerHTML = text;
}
</script>
</body>
</html>
DATE OBJECT
Method Description
getTimezone Returns the time difference between UTC time and local time, in
Offset() minutes
getUTCDate() Returns the day of the month, according to universal time (from 1-31)
getUTCDay() Returns the day of the week, according to universal time (from 0-6)
parse() Parses a date string and returns the number of milliseconds since
January 1, 1970
DATE OBJECT
Method Description
setUTCDate() Sets the day of the month of a date object, according to universal
time
toDateString() Converts the date portion of a Date object into a readable string
<<!DOCTYPE html>
<html>
<body>
<button onclick="myFunction()">Print Date</button>
<script>
function myFunction() {
var d = new Date();
var m = d.getMonth();
var day = d.getDay();
document.write(d + "<br> ");
document.write("The Day is :"+ day + "<br>");
document.write(d.getHours()+":" +d.getMinutes()+":"+d.getSeconds()+"<br>");
document.write(d.getDate() +"/" +d.getMonth()+"/"+d.getFullYear()+"<br>");
d.setDate(23);
document.write(d.getDate() +"/" +d.getMonth()+"/"+d.getFullYear()+"<br>");
}
</script></body></html>
MATH OBJECT
The Math object allows you to perform mathematical tasks on numbers.
Constants
Math.E // returns Euler's number
Math.PI // returns PI
Math.SQRT2 // returns the square root of 2
Math.SQRT1_2 // returns the square root of 1/2
Math.LN2 // returns the natural logarithm of 2
Math.LN10 // returns the natural logarithm of 10
Math.LOG2E // returns base 2 logarithm of E
Math.LOG10E // returns base 10 logarithm of E
Method Description
STRING OBJECTS
A JavaScript string simply stores a series of characters like "John Doe".
A string can be any text inside quotes. You can use single or double quotes:
var answer = "It's alright";
var answer = "He is called 'Johnny'";
var answer = 'He is called "Johnny"';
String Length
The length of a string is found in the built in property length:
var txt = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
var sln = txt.length;
Special Characters
Because strings must be written within quotes, JavaScript will misunderstand this string:
var y = "We are the so-called "Vikings" from the north."
The string will be chopped to "We are the so-called ".
The solution to avoid this problem, is to use the \ escape character.
The backslash escape character turns special characters into string characters:
var x = 'It\'s alright';
var y = "We are the so-called \"Vikings\" from the north."
The escape character (\) can also be used to insert other special characters in a string.
This is the list of special characters that can be added to a text string with the backslash sign:
Code Outputs
\\ backslash
\n new line
\r carriage return
\t tab
\b backspace
\f form feed
String Methods
Method Description
concat() Joins two or more strings, and returns a copy of the joined
strings
replace() Searches a string for a value and returns a new string with the
value replaced
search() Searches a string for a value and returns the position of the
match
Expression Description
The ranges shown above are general; you could also use the range [0-3] to match any decimal digit
ranging from 0 through 3, or the range [b-v] to match any lowercase character ranging from b through v.
Quantifiers
The frequency or position of bracketed character sequences and single characters can be denoted by a
special character. Each special character has a specific connotation. The +, *, ?, and $ flags all follow a
character sequence.
Expressio Description
n
Expression Description
[^a-zA-Z] It matches any string not containing any of the characters ranging
from athrough z and A through Z.
Alphanumeric Itself
\t Tab (\u0009)
\n Newline (\u000A)
\xnn The Latin character specified by the hexadecimal number nn; for example,
\x0A is the same as \n
\uxxxx The Unicode character specified by the hexadecimal number xxxx; for
example, \u0009 is the same as \t
\cX The control character ^X; for example, \cJ is equivalent to the newline
character \n
Metacharacters
A metacharacter is simply an alphabetical character preceded by a backslash that acts to give the
combination a special meaning. For instance, you can search for a large sum of money using the '\d'
metacharacter:/([\d]+)000/, Here \d will search for any string of numerical character. The following table
lists a set of metacharacters which can be used in PERL Style Regular Expressions.
Character Description
. a single character
\S non-whitespace character
\d a digit (0-9)
\D a non-digit
\W a non-word character
Modifier Description
G Performs a global match that is, find all matches rather than stopping
after the first match.
Usage Pattern
1.Username [Min 8 Chars and /^[a-z0-9]{8,}/i
alpha numeric characters)
2. Email ID /^[a-z0-9._-]+@[a-z]+.[a-z.]{2,5}$/i
3. Date of Birth /^[0-9]{1,2}-[0-9]{1,2}-[0-9]{4}$/i
4. Mobile Number /^([+0-9]{1,3})?([0-9]{10,11})$/i
5. Web Site URL /^[http://]+[www]?.[0-9a-z_.]+.[a-z.]{2,5}$/i
6. Pincode /^[0-9]{6}$/i
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Registration Form</title>
function validate(form){
var name = form.name.value;
var email = form.email.value;
var username = form.username.value;
var password = form.password.value;
var gender = form.gender.value;
var errors = [];
if (!ck_name.test(name)) {
errors[errors.length] = "You valid Name .";
}
if (!ck_email.test(email)) {
errors[errors.length] = "You must enter a valid email address.";
}
if (!ck_username.test(username)) {
errors[errors.length] = "You valid UserName no special char .";
}
if (!ck_password.test(password)) {
errors[errors.length] = "You must enter a valid Password min 6 char.";
}
if (gender==0) {
errors[errors.length] = "Select Gender"; }
if (errors.length > 0) {
reportErrors(errors);
return false;
}
return true;
}
function reportErrors(errors){
var msg = "Please Enter Valide Data...\n";
for (var i = 0; i<errors.length; i++) {
var numError = i + 1;
msg += "\n" + numError + ". " + errors[i];
}
alert(msg);
}
</script>
</head>
<body id="public">
<div style="height:30px"></div>
<div id="container">
<div style="height:30px"></div>
<form autocomplete="off"
enctype="multipart/form-data" method="post" action="thanks.html" onSubmit="return
validate(this);" name="form">
With the object model, JavaScript gets all the power it needs to create dynamic HTML:
• JavaScript can change all the HTML elements in the page
• JavaScript can change all the HTML attributes in the page
• JavaScript can change all the CSS styles in the page
• JavaScript can remove existing HTML elements and attributes
• JavaScript can add new HTML elements and attributes
• JavaScript can react to all existing HTML events in the page
• JavaScript can create new HTML events in the page
What is the DOM?
The DOM is a W3C (World Wide Web Consortium) standard.
The DOM defines a standard for accessing documents:
"The W3C Document Object Model (DOM) is a platform and language-neutral interface that allows
programs and scripts to dynamically access and update the content, structure, and style of a document."
The W3C DOM standard is separated into 3 different parts:
• Core DOM - standard model for all document types
• XML DOM - standard model for XML documents
• HTML DOM - standard model for HTML documents
Example
The following example changes the content (the innerHTML) of the <p> element with id="demo":
Example
<html>
<body>
<p id="demo"></p>
<script>
document.getElementById("demo").innerHTML = "Hello World!";
</script>
</body>
</html>
In the example above, getElementById is a method, while innerHTML is a property.
The getElementById Method
The most common way to access an HTML element is to use the id of the element.
In the example above the getElementById method used id="demo" to find the element.
The innerHTML Property
The easiest way to get the content of an element is by using the innerHTML property.
The innerHTML property is useful for getting or replacing the content of HTML elements.
The HTML DOM Document
In the HTML DOM object model, the document object represents your web page.
The document object is the owner of all other objects in your web page.
If you want to access objects in an HTML page, you always start with accessing the document object.
Finding HTML Elements
Method Description
Method Description
Method Description
Method Description
EVENT HANDLING
What is an Event ?
JavaScript's interaction with HTML is handled through events that occur when the user or the browser
manipulates a page.
When the page loads, it is called an event. When the user clicks a button, that click too is an event. Other
examples include events like pressing any key, closing a window, resizing a window, etc.
Developers can use these events to execute JavaScript coded responses, which cause buttons to close
windows, messages to be displayed to users, data to be validated, and virtually any other type of response
imaginable.
Events are a part of the Document Object Model (DOM) Level 3 and every HTML element contains a set of
events which can trigger JavaScript Code.
Mouse Events
1)onmouseover/onmouseout
• When the mouse passes over an element
• onmouseover - JavaScript code is called when the mouse is placed over a specific link or an object
or area from outside that object or area
• onmouseout - JavaScript code is called when the mouse leaves a specific link or an object or area
from outside that object or area.
<!DOCTYPE html>
<html>
<head>
<script>
function bigImg(x) {
x.style.height = "64px";
x.style.width = "64px";
}
function normalImg(x) {
x.style.height = "32px";
x.style.width = "32px";
}</script></head><body>
<img onmouseover="bigImg(this)" onmouseout="normalImg(this)" border="0" src="smiley.gif"
alt="Smiley" width="32" height="32">
</body></html>
.Output:
2) onmousedown/onmouseup - When pressing/releasing a mouse button
<!DOCTYPE html>
<html>
<head>
<script>
function myFunction(elmnt, clr) {
elmnt.style.color = clr;
}
</script></head><body>
<p onmousedown="myFunction(this,'red')" onmouseup="myFunction(this,'green')">
Click the text to change the color.
</p></body></html>
Output:
Click Events
• onClick
• ondblClick
1) onclick Event Type
This is the most frequently used event type which occurs when a user clicks the left button of his mouse.
You can put your validation, warning etc., against this event type.
In an onClick event handler, JavaScript function is called when an object in a button (regular, radio, reset
and submit) is clicked, a link is pushed, a checkbox is checked or an image map area is selected. Except for
the regular button and the area, the onClick event handler can return false to cancel the action. For
example:
<INPUT TYPE="submit" NAME="mysubmit" VALUE="Submit" onClick="return confirm(`Are you sure you
want to submit the form?')">
Example
<html>
<head>
<script type="text/javascript">
<!--
function sayHello() {
alert("Hello World")
}
//-->
</script>
</head>
<body>
<p>Click the following button and see result</p>
<form>
<input type="button" onclick="sayHello()" value="Say Hello" />
</form> </body></html>
Output
Onchange() Event
• When the user selects the drop down value
• The onChange event handler executes JavaScript code when input focus exits the field
after the user modifies its text.
<!DOCTYPE html>
<html>
<head>
<script>
function preferedBrowser() {
prefer = document.forms[0].browsers.value;
alert("You prefer browsing internet with " + prefer);
}
</script>
</head>
<body>
<form>
Choose which browser you prefer:
<select id="browsers" onchange="preferedBrowser()">
<option value="Chrome">Chrome</option>
<option value="Internet Explorer">Internet Explorer</option>
<option value="Firefox">Firefox</option>
</select>
</form></body></html>
Output:
OnFocus() Event
• When an input field gets focused
<!DOCTYPE html>
<html>
<head>
<script>
function myFunction(x) {
x.style.background = "yellow";
}
</script>
</head>
<body>
Enter your name: <input type="text" onfocus="myFunction(this)">
</body>
</html>
Output:
Load Events
Onload() Event
• When the image has been loaded.
• An onLoad event occurs when a window or image finishes loading. For windows, this event
handler is specified in the BODY attribute of the window. In an image, the event handler will
execute handler text when the image is loaded. For example:
<IMG NAME="myimage" SRC="http://rhoque.com/ad_rh.jpg" onLoad="alert('You loaded myimage')">
<!DOCTYPE html>
<html>
<head>
<script>
function loadImage() {
alert("Image is loaded");
}
</script>
</head>
<body>
<img src="w3javascript.gif" onload="loadImage()" width="100" height="132">
</body>
</html>
Output:
Onunload() Event
•When the browser closes the document.
<!DOCTYPE html>
<html>
<head>
<script>
function myFunction() {
alert("Thank you for visiting W3Schools!");
}
</script>
</head>
<body onunload="myFunction()">
<h1>Welcome to my Home Page</h1>
<p>Close this window or press F5 to reload the page.</p>
</body>
</html>
Output:
A JavaScript can be executed when an event occurs, like when a user clicks on an HTML element.
To execute code when a user clicks on an element, add JavaScript code to an HTML event attribute:
onclick = Javascript
Examples of HTML events:
• When a user clicks the mouse
• When a web page has loaded
• When an image has been loaded
• When the mouse moves over an element
• When an input field is changed
• When an HTML form is submitted
• When a user strokes a key
In this example, the content of the <h1> element is changed when a user clicks on it:
<!DOCTYPE html>
<html>
<body>
<h1 onclick="this.innerHTML='Ooops!'">Click on this text!</h1>
</body>
</html>
In this example, a function is called from the event handler:
<!DOCTYPE html>
<html>
<body>
<h1 onclick="changeText(this)">Click on this text!</h1>
<script>
function changeText(id) {
id.innerHTML = "Ooops!";
}
</script>
</body>
</html>
</body>
</html>
The onmouseover and onmouseout Events
The onmouseover and onmouseout events can be used to trigger a function when the user mouses over,
or out of, an HTML element.
<!DOCTYPE html>
<html>
<body>
<div onmouseover="mOver(this)" onmouseout="mOut(this)"
style="background-color:#D94A38;width:120px;height:20px;padding:40px;">
Mouse Over Me</div>
<script>
function mOver(obj) {
obj.innerHTML = "Thank You"
}
function mOut(obj) {
obj.innerHTML = "Mouse Over Me"
}
</script>
</body>
</html>
The onmousedown, onmouseup and onclick Events
The onmousedown, onmouseup, and onclick events are all parts of a mouse-click. First when a mouse-
button is clicked, the onmousedown event is triggered, then, when the mouse-button is released, the
onmouseup event is triggered, finally, when the mouse-click is completed, the onclick event is triggered.
<!DOCTYPE html>
<html>
<body>
<div onmousedown="mDown(this)" onmouseup="mUp(this)"
style="background-color:#D94A38;width:90px;height:20px;padding:40px;">
Click Me</div>
<script>
function mDown(obj) {
obj.style.backgroundColor = "#1ec5e5";
obj.innerHTML = "Release Me";
}
function mUp(obj) {
obj.style.backgroundColor="#D94A38";
obj.innerHTML="Thank You";
}
</script>
</body>
</html>
The onfocus()
Change the background-color of an input field when it gets focus.
<!DOCTYPE html>
<html>
<head>
<script>
function myFunction(x) {
x.style.background = "yellow";
}
</script>
</head> <body>
Enter your name: <input type="text" onfocus="myFunction(this)">
<p>When the input field gets focus, a function is triggered which changes the background-color.</p>
</body>
</html>
Example:
Create a web page using two image files, which switch between one another as the mouse pointer moves
over the images. Use the on Mouse Over and on Mouse Out
<!DOCTYPE html>
<html><head>
<script>
function lighton() {
document.getElementById('myimage').src = "bulbon.gif";
}
function lightoff() {
document.getElementById('myimage').src = "bulboff.gif";
}
</script>
</head> <body>
<img id="myimage" onmousedown="lighton()" onmouseup="lightoff()" src="bulboff.gif" width="100"
height="180" />
<p>Click mouse and hold down!</p>
</body>
</html>
EXCEPTION HANDLING
There are three types of errors in programming: (a) Syntax Errors, (b) Runtime Errors, and (c) Logical
Errors.
Syntax Errors
Syntax errors, also called parsing errors, occur at compile time in traditional programming languages
and at interpret time in JavaScript.
Runtime Errors
Runtime errors, also called exceptions, occur during execution (after compilation/interpretation).
Logical Errors
Logic errors can be the most difficult type of errors to track down. These errors are not the result of a
syntax or runtime error. Instead, they occur when you make a mistake in the logic that drives your
script and you do not get the result you expected.
JavaScript implements the try...catch...finally construct as well as the throw operator to handle
exceptions.
You can catch programmer-generated and runtime exceptions, but you cannot catchJavaScript syntax
errors.
Here is the try...catch...finally block syntax −
<script type="text/javascript">
<!--
try {
// Code to run
[break;]
}
catch ( e ) { // Code to run if an exception occurs
[break;]
}
[ finally {
// Code that is always executed regardless of
// an exception occurring
}]
//--> </script>
The try block must be followed by either exactly one catch block or one finally block (or one of both). When
an exception occurs in the try block, the exception is placed in e and the catch block is executed. The
optional finally block executes unconditionally after try/catch.
<!DOCTYPE html>
<html><body>
<p>Please input a number between 5 and 10:</p>
<input id="demo" type="text">
<button type="button" onclick="myFunction()">Test Input</button>
<p id="message"></p>
<script>
function myFunction() {
var message, x;
message = document.getElementById("message");
message.innerHTML = "";
x = document.getElementById("demo").value;
try {
if(x == "") throw "empty";
if(isNaN(x)) throw "not a number";
x = Number(x);
if(x < 5) throw "too low";
if(x > 10) throw "too high";
}
catch(err) {
message.innerHTML = "Input is " + err;
}
}
</script> </body></html>
The finally Statement
The finally statement lets you execute code, after try and catch, regardless of the result:
try {
Block of code to try
}
catch(err) {
Block of code to handle errors
}
finally {
Block of code to be executed regardless of the try / catch result
}
Example:
<!DOCTYPE html>
<html>
<body>
<p>Please input a number between 5 and 10:</p>
<input id="demo" type="text">
<button type="button" onclick="myFunction()">Test Input</button>
<p id="message"></p>
<script>
function myFunction() {
var message, x;
message = document.getElementById("message");
message.innerHTML = "";
x = document.getElementById("demo").value;
try {
if(x == "") throw "is empty";
if(isNaN(x)) throw "is not a number";
x = Number(x);
if(x > 10) throw "is too high";
if(x < 5) throw "is too low";
}
catch(err) {
message.innerHTML = "Input " + err;
}
finally {
document.getElementById("demo").value = "";
}
}
</script>
</body>
</html>
JSON
INTRODUCTION
JSON: JavaScript Object Notation.
JSON is a syntax for storing and exchanging data.
JSON is text, written with JavaScript object notation.
Exchanging Data
When exchanging data between a browser and a server, the data can only be text.
JSON is text, and we can convert any JavaScript object into JSON, and send JSON to the server.
We can also convert any JSON received from the server into JavaScript objects.
This way we can work with the data as JavaScript objects, with no complicated parsing and translations.
Sending Data
If you have data stored in a JavaScript object, you can convert the object into JSON, and send it to a
server:
var myObj = {name: "John", age: 31, city: "New York"};
var myJSON = JSON.stringify(myObj);
window.location = "demo_json.php?x=" + myJSON;
Receiving Data
If you receive data in JSON format, you can convert it into a JavaScript object:
var myJSON = '{"name":"John", "age":31, "city":"New York"}';
var myObj = JSON.parse(myJSON);
document.getElementById("demo").innerHTML = myObj.name;
Storing Data
When storing data, the data has to be a certain format, and regardless of where you choose to store it,
text is always one of the legal formats.
JSON makes it possible to store JavaScript objects as text.
// Storing data:
myObj = {name: "John", age: 31, city: "New York"};
myJSON = JSON.stringify(myObj);
localStorage.setItem("testJSON", myJSON);
// Retrieving data:
text = localStorage.getItem("testJSON");
obj = JSON.parse(text);
document.getElementById("demo").innerHTML = obj.name;
What is JSON?
• JSON stands for JavaScript Object Notation
• JSON is a lightweight data-interchange format
• JSON is "self-describing" and easy to understand
• JSON is language independent *
JSON uses JavaScript syntax, but the JSON format is text only.
Text can be read and used as a data format by any programming language.
JSON Values
In JSON, values must be one of the following data types:
• a string
• a number
• an object (JSON object)
• an array
• a boolean
• null
In JavaScript values can be all of the above, plus any other valid JavaScript expression, including:
• a function
• a date
• undefined
In JSON, string values must be written with double quotes:
{ "name":"John" }
In JavaScript, you can write string values with double or single quotes:
{ name:'John' }
FUNCTION FILES
A common use of JSON is to read data from a web server, and display the data in a web page.
<div id="id01"></div>
<script>
function myFunction(arr) {
var out = "";
var i;
for(i = 0; i<arr.length; i++) {
out += '<a href="' + arr[i].url + '">' + arr[i].display + '</a><br>';
}
document.getElementById("id01").innerHTML = out;
}
</script>
<script src="myTutorials.js"></script>
Example Explained
1: Create an array of objects.
Use an array literal to declare an array of objects.
Give each object two properties: display and url.
Name the array myArray:
var myArray = [
{
"display": "JavaScript Tutorial",
"url": "https://www.w3schools.com/js/default.asp"
},
{
"display": "HTML Tutorial",
"url": "https://www.w3schools.com/html/default.asp"
},
{
"display": "CSS Tutorial",
"url": "https://www.w3schools.com/css/default.asp"
}
]
SQL
This example reads JSON data from a web server running PHP and MySQL:
<!DOCTYPE html>
<html>
<body>
<h1>Customers</h1>
<div id="id01"></div>
<script>
var xmlhttp = new XMLHttpRequest();
var url = "https://www.w3schools.com/js/customers_mysql.php";
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
myFunction(this.responseText);
}
}
xmlhttp.open("GET", url, true);
xmlhttp.send();
function myFunction(response) {
var arr = JSON.parse(response);
var i;
var out = "<table>";
for(i = 0; i < arr.length; i++) {
out += "<tr><td>" +
arr[i].Name +
"</td><td>" +
arr[i].City +
"</td><td>" +
arr[i].Country +
"</td></tr>";
}
out += "</table>";
document.getElementById("id01").innerHTML = out;
}
</script>
</body>
</html>
$outp = "[";
while($rs = $result->fetch_array(MYSQLI_ASSOC)) {
if ($outp != "[") {$outp .= ",";}
$outp .= '{"Name":"' . $rs["CompanyName"] . '",';
$outp .= '"City":"' . $rs["City"] . '",';
$outp .= '"Country":"'. $rs["Country"] . '"}';
}
$outp .="]";
$conn->close();
echo($outp);
?>
Assignment
3. If the user takes more than 3 mins to fill the form, it should
pop up an alert message saying 3 mins past.
NOTE: All JS scripts and CSS scripts should be created as external scripts.
ONLINE CERTIFICATIONS
SoloLearn – Javascript
https://www.sololearn.com/learning/1024
Assessment Schedule
Name of the
S.NO Start Date End Date Portion
Assessment
89
Text Books & References
TEXT BOOK:
Deitel and Deitel and Nieto, “Internet and World Wide Web - How
to Program”, Prentice Hall, 5th Edition, 2011.
REFERENCES:
Disclaimer:
This document is confidential and intended solely for the educational purpose of RMK Group of
Educational Institutions. If you have received this document through email in error, please notify the
system manager. This document contains proprietary information and is intended only to the
respective group / learning community as intended. If you are not the addressee you should not
disseminate, distribute or copy through e-mail. Please notify the sender immediately by e-mail if you
have received this document by mistake and delete this document from your system. If you are not the
intended recipient you are notified that disclosing, copying, distributing or taking any action in reliance
on the contents of this information is strictly prohibited.