KEMBAR78
Iwp Module 3 | PDF | Java Script | Document Object Model
0% found this document useful (0 votes)
37 views52 pages

Iwp Module 3

This document provides an overview of JavaScript, covering its basics such as functions, arrays, the Document Object Model (DOM), and event handling. It explains the differences between JavaScript and Java, how JavaScript works within HTML, and various data types and structures. Additionally, it includes examples of JavaScript code for operations like arithmetic, object creation, and array manipulation.

Uploaded by

mishravivek3500
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
37 views52 pages

Iwp Module 3

This document provides an overview of JavaScript, covering its basics such as functions, arrays, the Document Object Model (DOM), and event handling. It explains the differences between JavaScript and Java, how JavaScript works within HTML, and various data types and structures. Additionally, it includes examples of JavaScript code for operations like arithmetic, object creation, and array manipulation.

Uploaded by

mishravivek3500
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 52

Unit-3

JavaScript
JavaScript Basics –Functions
– Arrays – DOM(Document
Object Method) - Built-in
Objects -Regular Expression-
Event handling – Validation
Introduction
● What is it?
● How does it work?
● What is Java?
● Learning JavaScript
● JavaScript Statements
● JavaScript and HTML forms
What is Javascript?
3
The term JavaScript refers to the language and its implementations .
● a lightweight programming language ("scripting
language")
● used to make web pages interactive
● insert dynamic text into HTML (ex: user name)
● react to events (ex: page load user click)
● get information about a user's computer (ex:
browser type)
● perform calculations on user's computer (ex: form
validation)
What is JavaScript?
● Browsers have limited functionality
● Text, images, tables, frames
● JavaScript allows for interactivity
● Browser/page manipulation
● Reacting to user actions
● A type of programming language
● Easy to learn
● Developed by ,Brendan Eich-1995 at Netscape
Initially, JavaScript’s name changed several times:
● Its code name was Mocha.
● In the Netscape Navigator 2.0 betas (September
1995), it was called LiveScript.
● In Netscape Navigator 2.0 beta 3 (December 1995), it
got its final name, JavaScript
Javascript vs Java
5
● interpreted, not compiled
● more relaxed syntax and rules
● fewer and "looser" data types
● variables don't need to be declared
● errors often silent (few exceptions)
● key construct is the function rather than the class
● "first-class" functions are used in many situations
● contained within a web page and integrates with
its HTML/CSS content

CS380
JavaScript Allows Interactivity
● Improve appearance
● Especially graphics
● Visual feedback
● Site navigation
● Perform calculations
● Validation of input
● Other technologies
How Does It Work?
● Embedded within HTML page
● View source
● Executes on client
● Fast, no connection needed once loaded
● Simple programming statements combined with
HTML tags
● Interpreted (not compiled)
● No special tools required
JavaScript Statements
<html>
<head><title>My Page</title></head>
<body>
<script language="JavaScript">

document.write('This is my first →
JavaScript Page');

</script>
Note the symbol for
</body> line continuation
</html>
JavaScript Statements
<html>
<head><title>My Page</title></head>
<body>
<script language=“JavaScript">

document.write('<h1>This is my first →
JavaScript Page</h1>');

</script>
HTML written
</body>
inside JavaScript
</html>
Data Types
1.String
<html>
2. Number <body>
3. Bigint- modular <h1></h1>Bigint</h1>
arithmetic, GCD <p id="demo"></p>
calculation, primality
<script>
testing, bit
let x = BigInt("123456789012345678901234567890");
manipulation document.getElementById("demo").innerHTML = x;
4. Boolean </script>
5. Undefined
6. Null </body>
</html>
7. Symbol
8. Object
Objects
● An object is a collection of named properties
● Think of it as an associative array or hash table
● Set of name:value pairs
● objBob
slide 11 = {name: “Bob", grade: 'A', level: 3};

● New members can be added at any time


● objBob.fullname = 'Robert';
Variables in JavaScript
• Variables are containers which hold reusable data.
String Concatenation
var university= VIT;
alert(university);
var a= “VIT Bhopal”;

var b=“VIT Vellore”;


Note: var University = “VIT Bhopal”;
var university = “VIT Vellore”; var c= a+b;
alert(university);
alert(c);
Functions
● Functions are objects with method called “( )”
● A property of an object may be a function (=method)
● function max(x,y) { if (x>y) return x; else return y;};
slide 13
● max.description = “return the maximum of two arguments”;
● Local declarations may appear in function body
● Call can supply any number of arguments
● functionname.length : # of arguments in definition
● functionname.arguments.length : # arguments in call
● Basic types are passed by value, objects by reference
● “Anonymous” functions
● (function (x,y) {return x+y}) (2,3);
Functions
• JavaScript functions are used to perform operations. We can call JavaScript
function many times to reuse the code.
We can call a function several times so it save coding.
We don’t need to write many lines of code each time to perform a common
task.
• <html>
Syntax
• <body> • function<functionName>(){
• <script> }
• function msg(){
• alert("hello!"); • function<functionName>(a,b){
• } }
• </script>
• <input type="button" onclick="msg()" value=“function"/>
• </body>
• </html>
Return Value

•<script>
• function getInfo(){
• return " Hello!";
• }
• </script>
• <script>
• document.write(getInfo());
• </script>
Date and Time
<html>
<body>

<h2>Todays Date and Time </h2>

<button type="button"
onclick="document.getElementById('demo').innerHTML =
Date()">
Date and Time.</button>

<p id="demo"></p>

</body>
</html>
Arithmetic
<html>
<body>

<h1>JavaScript Arithmetic</h1>
<h2>Operator Precedence</h2>
<p> Arithmetic</p>

<p id="demo"></p>

<script>
document.getElementById("demo").innerHTML = 200 / 40 * 3;
</script>

</body>
</html>
JavaScript Program to Print-Hello
1. using console.log- debugging the code
2. using alert()- display alert box on the current window.
3. using document.write()- print the content to the html
4. using confirm()- confirm/cancel depending upon users
click.
5.using prompt()- dialogue for user input

External JavaScript
<script type=“text/javascript”> <script src=“myscript.js”></script”>
console.log(“Hello”);
alert(“Hello”);
document.write(“Hello”);
</script>
• Browser Object Model
The Browser Object Model (BOM) is
used to interact with the browser.

Window- (1) document


(2) history
(3) screen
(4) navigator
(5) location
• Navigator object
<html>
<body>
<h2>JavaScript Navigator Object</h2>
<script>
document.writeln("<br/>navigator.appCodeName: "+navigator.appCodeName);
document.writeln("<br/>navigator.appName: "+navigator.appName);
document.writeln("<br/>navigator.appVersion: "+navigator.appVersion);
document.writeln("<br/>navigator.cookieEnabled: "+navigator.cookieEnabled);
document.writeln("<br/>navigator.language: "+navigator.language);
document.writeln("<br/>navigator.userAgent: "+navigator.userAgent);
document.writeln("<br/>navigator.platform: "+navigator.platform);
document.writeln("<br/>navigator.onLine: "+navigator.onLine);

</script>
</body>
</html>
• Document Object Model
The Document Object Model (DOM) is
used to represents the whole html
document.
Document.getElementById()
Document.getElementsByClassName()
innerHTML()
• innerHTML
-It is used mostly in the web pages to generate the dynamic html such as registration
form, comment form, links .

• innerText
-Text will not be interpreted as html text but a normal text
• Document Object Model
write("string") writes the given string on the
doucment.
writeln("string") newline character at the end.

getElementById() returns the element having the


given id value.
getElementsByName() returns all the elements having the
given name value.
getElementsByTagName() returns all the elements having the
given tag name.
getElementsByClassName() returns all the elements having the
given class name.
• document.getElementById()
method
<body>
<div id=“Employee”>
HCL
</div>
</body>
<script type=“text/javascript”>
var k= document.getElementByID(“Employee”);
alert(k);
</script>
</html>
• document.getElementsByClassNa
me() method
<body>
<div class=“Employee”>
HCL
</div>
</body>
<script type=“text/javascript”>
var a=
document.getElementsByClassName(“Employee”).innerHTML;
alert(a);
</script>
</html>
• document.getElementById()
method
<script type="text/javascript">
function getcube(){
var number=document.getElementById("number").value;
alert(number*number*number);
}
</script>
<form>
Enter No:<input type="text" id="number"
name="number"/><br/>
<input type="button" value="cube" onclick="getcube()"/>
• document.getElementsByTagName
() method
<script type="text/javascript">
function countpara(){
var totalpara=document.getElementsByTagName("p");
alert("total p tags are: "+totalpara.length);

}
</script>
<p>This is a pragraph</p>
<p>Here we are going to count total number of paragraphs by
getElementByTagName() method.</p>
<p>Let's see the simple example</p>
<button onclick="countpara()">count paragraph</button>
• document.getElementsByName()
method
<script type="text/javascript">
function totalelements()
{
var allgenders=document.getElementsByName("gender");
alert("Total Genders:"+allgenders.length);
}
</script>
<form>
Male:<input type="radio" name="gender" value="male">
Female:<input type="radio" name="gender" value="female">
Transgender:<input type="radio" name="gender" value=“transgender">

<input type="button" onclick="totalelements()" value="Total Genders">


</form>
Operators +,-,*,/
<html>
<body>
<h1>Arithmetic</h1>
<h2>Operator</h2>
<p id="demo"></p>
<script>
let x = 2890900;
let y = 9076564567899;
let z = x + y;
document.getElementById("demo").innerHTML = z;
</script>
</body>
</html>
Write Code for Calculator using
HTML,CSS and Java Script
Object literals
● You don’t declare the types of variables in JavaScript
● JavaScript has object literals, written with this syntax:
– { name1 : value1 , ... , nameN : valueN }

● Example:
– car = {myCar: "Saturn", 7: "Mazda",
getCar: CarTypes("Honda"), special: Sales}
● The fields are myCar, getCar, 7 (this is a legal field name) ,
and special
• "Saturn" and "Mazda" are Strings
• CarTypes is a function call
• Sales is a variable you defined earlier

● Example use: document.write("I own a " + car.myCar);


Three ways to create an object
● You can use an object literal:
– var course = { number: “23", teacher=“XYZ" }
● You can use new to create a “blank” object, and add fields
to it later:
– var course = new Object();
course.number = “23";
course.teacher = “XYZ";
● You can write and use a constructor:
– function Course(n, t)
– this.number = n;
this.teacher = t;
}
– var course = new Course(“23", “XYZ");
Array
• An object that represents a collection of similar type of elements.
Method 1
• Var house=[];
// initializing while declaring
• Var house =[“1BHK”, “2BHK”];
Or // initializing after declaring
• House[0]=“1BHK”;
• House[1]=“2BHK”;

Method 2
• Varhouse=newarray()
• Var house=new array(10,20);
Or// storing number
• Var house=[“1BHK”,20];
Array literals
● You don’t declare the types of variables in JavaScript
● JavaScript has array literals, written with brackets and
commas
● Example: color = ["red", "yellow", "green", "blue"];
● Arrays are zero-based: color[0] is "red"
● If you put two commas in a row, the array has an “empty”
element in that location
● Example: color = ["red", , , "green", "blue"];
• color has 5 elements
● However, a single comma at the end is ignored
● Example: color = ["red", , , "green", "blue”,]; still has 5 elements
Four ways to create an array
● You can use an array literal:
var colors = ["red", "green", "blue"];
● You can use new Array() to create an empty array:
– var colors = new Array();
● You can add elements to the array later:
colors[0] = "red"; colors[2] = "blue"; colors[1]="green";
● You can use new Array(n) with a single numeric argument
to create an array of that size
– var colors = new Array(3);
● You can use new Array(…) with two or more arguments to
create an array containing those values:
– var colors = new Array("red","green", "blue");
Arrays and objects
● Arrays are objects
• car = { myCar: "Saturn", 7: "Mazda" }
– car[7] is the same as car.7
– car.myCar is the same as car["myCar"]
● If you know the name of a property, you can use
dot notation: car.myCar
● If you don’t know the name of a property, but you
have it in a variable (or can compute it), you must
use array notation: car.["my" + "Car"]
Array

1. JavaScript Array literal


<html>
<body>
<script>
var emp=[“Suman",“Shyam",“Shubham"];
for (i=0;i<emp.length;i++){
document.write(emp[i] + "<br/>");
}
</script>
</body>
</html>
2. JavaScript Array directly

<html>
<body>
<script>
var i;
var emp = new Array();
emp[0] = "x";
emp[1] = "y";
emp[2] = "z";
for (i=0;i<emp.length;i++){
document.write(emp[i] + "<br>");
}
</script>
</body>
</html>
3. JavaScript Array Constructor
(By passing arguments in constructor so that
we don't have to provide value explicitly)
<script>
var emp=new Array(“Richa",“Rekha",“Ravi");
for (i=0;i<emp.length;i++){
document.write(emp[i] + "<br>");
}
</script>
• JavaScript Array Methods
• valueOf()- to print the data of array.
• isArray()- check if the variable is an array or
not?
• concat()- join several arrays into one
• indexOf()-Returns the primitive value of the
specified object
• Join()- Combine elements of an array into a
single and return the string
• JavaScript using an Array-concat()
<html>
<body>
<script>
var arr=[“R",“Ruby","Python"];
var result= arr.concat(“SPSS",“Friedmen Test", "Android");
document.writeln(result);
</script>
</body>
</html>
• JavaScript using an Array-concat()
<html>
<body>
<script>
var arr=[“R",“Ruby","Python"];
var result= arr.concat(“SPSS",“Friedmen Test", "Android");
document.writeln(result);
</script>
</body>
</html>
The for…in statement
● You can loop through all the properties of an object with
for (variable in object) statement;
● Example: for (var prop in course) {
document.write(prop + ": " + course[prop]);
}
● Possible output: teacher: Dr. Dave
number: CIT597
● The properties are accessed in an undefined order
● If you add or delete properties of the object within the loop, it is
undefined whether the loop will visit those properties
● Arrays are objects; applied to an array, for…in will visit the
“properties” 0, 1, 2, …
● Notice that course["teacher"] is equivalent to course.teacher
● You must use brackets if the property name is in a variable
The with statement
• with (object) statement ; uses the object as the
default prefix for variables in the statement
● For example, the following are equivalent:
– with (document.myForm) {
result.value = compute(myInput.value) ;
}
– document.myForm.result.value =
compute(document.myForm.myInput.value);
● One of my books hints at mysterious problems
resulting from the use of with, and recommends
against ever using it
Regular expressions
● A regular expression can be written in either of two ways:
● Within slashes, such as re = /ab+c/
● With a constructor, such as re = new RegExp("ab+c")
● Regular expressions are almost the same as in Perl or Java
(only a few unusual features are missing)
● string.match(regexp) searches string for an occurrence of
regexp
● It returns null if nothing is found
● If regexp has the g (global search) flag set, match returns an array
of matched substrings
● If g is not set, match returns an array whose 0th element is the
matched text, extra elements are the parenthesized
subexpressions, and the index property is the start position of the
matched substring
• Exception Handling
An exception is the anomalous code
that breaks the normal flow of the
code.
An abnormal condition occurs.
1. Syntax Error
2. Runtime Error
3. Logical Error
• Error Object
1. Name- returns an error name
2. Message-error message in the string form
• Built-in error
1. EvalError-an instance for the error that occurred in the eval()
2. InternalError-an instance when the js engine throws an
internal error.
3. RangeError- parameter is out of its valid range
4. ReferenceError-invalid reference is de-referenced
5. SyntaxError-while parsing the eval()
6. TypeError- an instance is created for such an error.
7. URIError- invalid parameters are passed
in encodeURI() or decodeURI()
• Exception Handling
Statements
1. throw -User can define and throw their own custom errors.

2. try…catch –any error occur, it passes to the catch{} block for


taking suitable actions and handle the error

3. try…catch…finally- Finally block does not hold for the


exception to be thrown.
-It does not care for the output.
•try catch
try{
expression; }
catch(error){
expression; }
error.
•throw
<html>
<head>Exception Handling</head>
<body>
<script>
try {
throw new Error('This is the throw keyword'); //user-defined throw statement.
}
catch (e) {
document.write(e.message); // This will generate an error message
}
</script>
</body>
</html>
• try catch finally
<html>
<head>Exception Handling</head>
<body>
<script>
try{
var a=2;
if(a==2)
document.write("ok");
}
catch(Error){
document.write("Error found"+e.message);
}
finally{
document.write("Value of a is 2 ");
}
</script>
</body>
</html>
• Validation
• JavaScript provides facility to validate the form on the client-side so data processing
will be faster than server-side validation.
<html>
<body>
<script>
<form name="myform" method="post"
function validateform(){
action="http://www.javatpoint.com/jav
var name=document.myform.name.value; ascriptpages/valid.jsp"
var password=document.myform.password.value; onsubmit="return validateform()" >
Name: <input type="text"
if (name==null || name==""){ name="name"><br/>
alert("Name can't be blank"); Password: <input type="password"
return false; name="password"><br/>
}else if(password.length<6){ <input type="submit"
alert("Password must be at least 6 characters long."); value="register">
return false; </form>
} </body>
</html>
}
</script>
<body>

You might also like