0% found this document useful (0 votes)
12 views31 pages

Unit III BSC Javascript Css

This document provides an overview of JavaScript, including its role in web programming, key concepts such as DHTML, and the differences between HTML and DHTML. It covers JavaScript basics, including variables, data types, string manipulation, and mathematical functions, as well as the advantages and challenges of using JavaScript. Additionally, it explains how to include JavaScript in HTML documents and introduces alternative scripting languages.

Uploaded by

rajannad99
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)
12 views31 pages

Unit III BSC Javascript Css

This document provides an overview of JavaScript, including its role in web programming, key concepts such as DHTML, and the differences between HTML and DHTML. It covers JavaScript basics, including variables, data types, string manipulation, and mathematical functions, as well as the advantages and challenges of using JavaScript. Additionally, it explains how to include JavaScript in HTML documents and introduces alternative scripting languages.

Uploaded by

rajannad99
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/ 31

lOMoARcPSD|54064683

UNIT-III BSC - Javascript css

web programming (Kakatiya University)

Scan to open on Studocu

Studocu is not sponsored or endorsed by any college or university


Downloaded by Rajesh D ([email protected])
lOMoARcPSD|54064683

UNIT – III
Introduction to JavaScript
What is DHTML, JavaScript, basics, variables, string manipulations, mathematical functions, statements,
operators, arrays, functions.
Objects in JavaScript: Data and objects in JavaScript, regular expressions, exception handling
………………………………………………………………………………………………………………………….
1.What is DHTML?
Dynamic HTML, or DHTML, is an umbrella term for a collection of technologies used together to create
interactive and animated websites by using a combination of a static markup language (such as HTML), a
client-side scripting language (such as JavaScript), a presentation definition language (such as CSS), and the
Document Object Model (DOM). The application of DHTML was introduced by Microsoft with the
release of Internet Explorer 4 in 1997.

Differences between HTML and DHTML:


 HTML is a mark-up language, while DHTML is a collection of technology.
 DHTML creates dynamic web pages, whereas HTML creates static web pages.
 DHTML allows including small animations and dynamic menus in Web pages.
 DHML used events, methods, properties to insulate dynamism in HTML Pages.
 DHML is basically using JavaScript and style sheets in an HTML page.
 HTML sites will be slow upon client-side technologies, while DHTML sites will be fast enough upon
client-side technologies.
 HTML creates a plain page without any styles and Scripts called as HTML. Whereas, DHTML creates
a page with HTML, CSS, DOM and Scripts called as DHTML.
 HTML cannot have any server side code but DHTML may contain server side code.
 In HTML, there is no need for database connectivity, but DHTML may require connecting to a
database as it interacts with user.
 HTML files are stored with .htm or .html extension, while DHTML files are stored with .dhtm
extension.

1 © www.anuupdates.org Prepared by Dodda. Venkata Reddy M.Tech

Downloaded by Rajesh D ([email protected])


lOMoARcPSD|54064683

 HTML does not require any processing from browser, while DHTML requires processing from
browser which changes its look and feel.

2. JavaScript
A JavaScript is a scripting language used at the client side design along with HTML,CSS, and XML. The
main use of JavaScript is to validate the data present in a web application. One can also control the web
application using JavaScript.
Example: For example, when your login into a Facebook page account you need to provide correct user
name and password. If anything went wrong it display an error message. That means someone at the
background validating the username and password. This type of validation can be done using JavaScript.
Benefits / Advantages of JavaScript
 JavaScript has a number of big benefits to anyone who wants to make their website dynamic.
 It is widely supported in web browsers
 It gives easy access to the document object and can manipulate most of them.
 JavaScript can give interesting animations without the long download times associated with many
multimedia data types.
 Web servers don’t need a special plugin to your scripts.
 JavaScript is relatively easy.
Problems with Java Script
 Most scripts relay upon manipulating the elements of the DOM. Support for standard set of objects
currently does not exist and access to objects differs from browser to browser.
 If your script does not work then your page is useless.
 Because of the problem of broken scripts many web pages suffers disable JavaScript support in their
browsers.
 Scripts can run slowly and complex scripts can take a long time to startup.

Note

Plugin: plugin is small application which handle specific data type and which may either run as
standard alone application or embedded within the browser.

2 © www.anuupdates.org Prepared by Dodda. Venkata Reddy M.Tech

Downloaded by Rajesh D ([email protected])


lOMoARcPSD|54064683

3. JavaScript Basic

a) Including JavaScript in your HTML Page.


We can include JavaScript in two areas of a HTML document. The script is included in the webpage and
run by the browser usually as soon as the page loaded. The browser is able to debug the script and can
display errors.
In HTML, JavaScript code must be inserted between <script> and </script> tags.
i) ) Including JavaScript in Header section.
The JavaScript which is included in the header section of the webpage will be run as soon as the web
browser is loaded and it is sometimes useful to execute a function that result when the browser is loaded.
Example:
<!DOCTYPE html>
<html>
<head>
<script>
function myFunction() {
document.getElementById("demo").innerHTML = "Paragraph changed.";
}
</script>
</head>
<body>

<h2>JavaScript in Head</h2>

<p id="demo">A Paragraph.</p>

<button type="button" onclick="myFunction()">Try it</button>

</body>
</html>

ii) Including JavaScript in body section.


One can include the JavaScript in the body section when they want to execute some of the functions like
validating the text, event handling etc. The code inside the body react depending upon the conditions or
code present in the HTML document.
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript in Body</h2>
<p id="demo">A Paragraph.</p>
<button type="button" onclick="myFunction()">Try it</button>
<script>
function myFunction() {
document.getElementById("demo").innerHTML = "Paragraph changed.";
}
</script>

3 © www.anuupdates.org Prepared by Dodda. Venkata Reddy M.Tech

Downloaded by Rajesh D ([email protected])


lOMoARcPSD|54064683

</body>
</html>

iii) Using external JavaScript file.

If we use a lot of scripts or our scripts are complex then including the code inside the webpage will
make your source file difficult to read and debug. We can put JavaScript code in a separate file and
include the code in the head of the webpage. JavaScript programs are stored in files with the .js extension.

myScript.js

function myFunction() {
document.getElementById("demo").innerHTML = "Paragraph changed.";
}

To use an external script, put the name of the script file in the src (source) attribute of a <script> tag:

<script src="myScript.js"></script>

Example:

<!DOCTYPE html>
<html>
<body>
<h2>External JavaScript</h2>
<p id="demo">A Paragraph.</p>
<button type="button" onclick="myFunction()">Try it</button>
<p>(myFunction is stored in an external file called "myScript.js")</p>
<script src="myScript.js"></script>
</body>
</html>

b) Input and output statements in JavaScript

Input: In JavaScript the input is get by using prompt box. This function frames a window object and
its general form is

Syntax: Window.prompt (“ “, variable name);


Example: Window.prompt (“enter your name”, name);

Output: In JavaScript t he data can be displayed on the web page by using two functions: write() and
writeln(). The general form is

Syntax: window. write(“message”, variable name);


window. writeln(“message”, variable name);

4 © www.anuupdates.org Prepared by Dodda. Venkata Reddy M.Tech

Downloaded by Rajesh D ([email protected])


lOMoARcPSD|54064683

c) Data types in JavaScript:


Like all other languages JavaScript also supports data types. A data type represents the type of the
data and the operations that can be performed on that data. JavaScript supports four types of data types.

1. Numerical data types: These are the basic numbers it can include all the integers, fractions and
expression data.

Example: Numeric a=10;

2. String data type: These are collection of characters or a single character in the double quotes. The string
data type can also store numbers represented in the form of string using double quotes.

Example: string s=”c”;


String s1=”1234”;

3. Boolean data type: Boolean variables hold the values “ true” and “false”. These are used a lot in
programming to hold results of conditional text.

4. Null data types: This is used when you don’t know something. A Null value means one that has been
decided.

d) Alternatives to JavaScript:

There are so many alternative solutions to the problem of making websites interactive and dynamic.
Some of these rely upon complex multimedia data, while others are script based. Some of the scripting
solutions which might be consider as competitors to JavaScript are listed below.

Perl: A complex language that is commonly used for server side CGI scripting. Perl is available for client
side work through a subset called PerlScript which can also be used when writing active server pages.

VBScript: widely used but unfortunately platform specific. This language is only available under the
Microsoft windows operating system.

Python: A little known languages that is making inroads into the CGI writing area. A web browser has
been written in Python which can run Python applets.

TCL: This has been a popular choice for systems programming. The language itself has been widely
criticised by proponents of other scripting languages but it is clearly effective in its own niche.

Java: This is a scripting language but it is used for many of the same things as JavaScript. It’s very good at
menus and data validation on the client but can be very slow.

5 © www.anuupdates.org Prepared by Dodda. Venkata Reddy M.Tech

Downloaded by Rajesh D ([email protected])


lOMoARcPSD|54064683

4. Variables in JavaScript

Like any programming languages JavaScript has variables. These are data items that you can manipulate
as program the program runs. A variable is a named value that you use in your program.

Rules for variables

1. Variable name must starts with a letter or underscore


2. You can’t use spaces while giving variable names.
3. Names are case sensitive.
4. You can’t use reserved words as variable names. Reserved words are those words which are part of
JavaScript language which have special meaning and purpose.

Creating variables:

The variable declaration tells what type of data we are using in your JavaScript. Like other languages
JavaScript also provides variables. When you declare a variable we can’t use its type instead JavaScript use
“var” keyword to create variables. This keyword is placed before the variable name.

Syntax: var Variable Name;

Example: var a;

<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Variables</h2>
<p>In this example, x, y, and z are variables.</p>
<p id="demo"></p>
<script>
var x = 5;
var y = 6;
var z = x + y;
document.getElementById("demo").innerHTML =
"The value of z is: " + z;
</script>
</body>
</html>

6 © www.anuupdates.org Prepared by Dodda. Venkata Reddy M.Tech

Downloaded by Rajesh D ([email protected])


lOMoARcPSD|54064683

5. String Manipulation / String Functions / String Object

A sting is collection of characters. The sting object is used to manipulate a stored piece of text, String
objects are created as,

Var t1= new String (“hello”);

Or

Var t1= “hello”

JavaScript has functions which perform different operations on stings such as string comparison, searching
a string in another string, converting from one case to another one.

1. String Length: The length property returns the length of string

Example: Var s1=”hello”;


S1.length;

The above example returns the length of string as 5.

2. Finding a String in a String

The indexOf() method returns the index of (the position of) the first occurrence of a specified text in
a string.

Example: s1
h e l l o
0 1 2 3 4
Var s1=”hello”;
indexOf(l);
In the above example, the indexOf() returns index position 2.

The lastIndexOf() method returns the index of the last occurrence of a specified text in a string.

Example: Var s1=”hello”;


lastIndexOf(l);
In the above example, lastIndexOf() returns index position 3.

 Both indexOf(), and lastIndexOf() return -1 if the text is not found.

3. Extracting String Parts

There are 3 methods for extracting a part of a string:


 slice(start, end)

7 © www.anuupdates.org Prepared by Dodda. Venkata Reddy M.Tech

Downloaded by Rajesh D ([email protected])


lOMoARcPSD|54064683

 substring(start, end)
 substr(start, length)

The slice() Method

 slice() extracts a part of a string and returns the extracted part in a new string.
 The method takes 2 parameters: the start position, and the end position (end not included).

This example slices out a portion of a string from position 7 to position 12 (13-1):

Example:

var str = "Apple, Banana, Kiwi";


var res = str.slice(7, 13);

The result of res will be: Banana

The substring() Method

 substring() is similar to slice().


 The difference is that substring() cannot accept negative indexes.

Example:

var str = "Apple, Banana, Kiwi";


var res = str.slice(7, 13);

The result of res will be: Banana

The substr() Method


 substr() is similar to slice().
 The difference is that the second parameter specifies the length of the extracted part.

Example:
var str = "Apple, Banana, Kiwi";
var res = str.slice(7, 6);

The result of res will be: Banana

4. Replacing String Content

The replace() method replaces a specified value with another value in a string.

Example:
str = "Please visit Microsoft!";
var n = str.replace("Microsoft", "W3Schools");

8 © www.anuupdates.org Prepared by Dodda. Venkata Reddy M.Tech

Downloaded by Rajesh D ([email protected])


lOMoARcPSD|54064683

The value of ‘n’ will be ‘Please visit W3Schools’

 The replace() method does not change the string it is called on. It returns a new string.
 By default, the replace() method replaces only the first match.
 By default, the replace() method is case sensitive.

5. Converting to Upper and Lower Case

A string is converted to upper case with toUpperCase().

Example:

var text1 = "Hello World!"; // String


var text2 = text1.toUpperCase(); // text2 is text1 converted to upper

A string is converted to lower case with toLowerCase()

Example:

var text1 = "Hello World!"; // String


var text2 = text1.toLowerCase(); // text2 is text1 converted to lower
6. The concat() Method
concat() joins two or more strings:
Example:
var text1 = "Hello";
var text2 = "World";
var text3 = text1.concat(" ", text2);

7. String.trim()

The trim() method removes whitespace from both sides of a string:


Example:
var str = " Hello World! ";
alert(str.trim());

8. Extracting String Characters

The charAt() Method


The charAt() method returns the character at a specified index (position) in a string:
Example:
var str = "HELLO WORLD";
str.charAt(0); // returns H

Note:
All string methods return a new string. They don't modify the original string.

9 © www.anuupdates.org Prepared by Dodda. Venkata Reddy M.Tech

Downloaded by Rajesh D ([email protected])


lOMoARcPSD|54064683

Formally said: Strings are immutable: Strings cannot be changed, only replaced.

6. Mathematical Functions / Math Object


Mathematical functions and values are part of a built in JavaScript object called Math. All functions and
attributes used in complex mathematics must be accessed via this object.
 NaN: This is value which represents something which is not a number. If any mathematical
calculation returns other than number format then the JavaScript outputs those results as NaN.
 abs(value): Returns the absolute value the number passed into it.
 acos (value), asin(value), atan(value): These functions return the arccosine, arcsine and arctangent
respectively of the value passed into them. All return values are in radians.
 atan2(value): Returns the arctangent, in radios, of the quotient of the values passed into it.
 ceil(value): Returns the smallest integer which is greater than or equal to the value passed in.
 cos(value), sin(value), tan(value): These return the cosine, sin and tangent respectively of the value
passed in as an argument.
 floor(value): returns the largest which is smaller than or equal the number passed in.
 isNan(value): This function returns true if its argument is not a number and false if it is numeric.
 long(value): Returns the natural logarithm of its argument.
 Max(value1, value2): Returns the large of its arguments.
 Min(value1, value2): Returns the smaller of its arguments.
 parseInt(string, radix): The string is parsed and its value as an integer returned.
 parseFloot(sting): This function parses a string passed in as argument and returns it as a floating
point number.
 Pow(value,power): Returns the result of raising value to power.
 Sqrt(value): Returns the square root of the value.

7. Statements in JavaScript
JavaScript supports three types of statements branching statements, looping statements, jumping
statements.
i) Branching statements
The conditional branching statements help to
jump from one part of the program to another
depending on whether a particular condition is satisfied
or not. Generally they are two types of branching
statements.
a) if-else statement:
Whenever you want to test the truth of a
condition before executing any more of your program,
use this construct. This statement means that if some
condition is true then do one thing, if the condition is
false do another.

10 © www.anuupdates.org Prepared by Dodda. Venkata Reddy M.Tech

Downloaded by Rajesh D ([email protected])


lOMoARcPSD|54064683

Syntax:
If(condition{
// do some thing
}
else
{
// do another
}

Example program:
<html>
<head>
<title>IF Statments!!!</title>
<script type="text/javascript">
var age = prompt("Please enter your age");
if(age>=18)
document.write("You are an adult <br />");
if(age<18)
document.write("You are NOT an adult <br />");
</script>
</head>
<body>
</body>
</html>

b) Switch statement

The switch statement is used to perform different actions based on different conditions. JavaScript Use
the switch statement to select one of many code blocks to be executed.
Syntax:
switch(expression) {
case x:
// code block
break;
case y:
// code block
break;
default:
// code block
}
This is how it works:
 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.

11 © www.anuupdates.org Prepared by Dodda. Venkata Reddy M.Tech

Downloaded by Rajesh D ([email protected])


lOMoARcPSD|54064683

Example:
<!DOCTYPE html>
<html>
<body>
<p id="demo"></p>
<script>
var day;
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";
}
document.getElementById("demo").innerHTML = "Today is " + day;
</script>
</body>
</html>

2. Looping statements

Loops are handy, if you want to run the same code over and over again, each time with a different value.
Often this is the case when working with arrays; Instead of assigning each value using index, we read and
print values using loops.
JavaScript supports different kinds of loops:
 for - loops through a block of code a number of times

 for-in: - loops through the properties of an object

 while - loops through a block of code while a specified condition is true

 do-while: - also loops through a block of code while a specified condition is true

12 © www.anuupdates.org Prepared by Dodda. Venkata Reddy M.Tech

Downloaded by Rajesh D ([email protected])


lOMoARcPSD|54064683

a) for loop:

The for loop has the following syntax:


for (statement 1; statement 2; statement 3) {
// code block to be executed
}
Statement 1 is executed (one time) before the execution of the code block.
Statement 2 defines the condition for executing the code block.
Statement 3 is executed (every time) after the code block has been executed.

<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Loops</h2>
<p id="demo"></p>
<script>
var text = "";
var i;
for (i = 0; i < 5; i++) {
text += "The number is " + i + "<br>";
}
document.getElementById("demo").innerHTML = text;
</script>
</body>
</html>

b) for-in: The JavaScript for/in statement loops through the properties of an object:
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Loops</h2>
<p>The for/in statement loops through the properties of an object.</p>
<p id="demo"></p>
<script>
var txt = "";
var person = {fname:"John", lname:"Doe", age:25};
var x;
for (x in person) {
txt += person[x] + " ";
}
document.getElementById("demo").innerHTML = txt;
</script>
</body>
</html>

13 © www.anuupdates.org Prepared by Dodda. Venkata Reddy M.Tech

Downloaded by Rajesh D ([email protected])


lOMoARcPSD|54064683

c) While statement

The while loop loops through a block of code as long as a specified condition is true.

Syntax:
while (condition) {
// code block to be executed
}

<!DOCTYPE html>
<html>
<body>
<h2>JavaScript while</h2>
<p id="demo"></p>
<script>
var text = "";
var i = 0;
while (i < 10) {
text += "<br>The number is " + i;
i++;
}
document.getElementById("demo").innerHTML = text;
</script>
</body>
</html>

d) do-wile statement

The do-while loop is a variant of the while loop. This loop will execute the code block once, before
checking if the condition is true, and then it will repeat the loop as long as the condition is true.
Syntax:
do {
// code block to be executed
}while (condition);

<!DOCTYPE html>
<html>
<body>
<h2>JavaScript do ... while</h2>
<p id="demo"></p>
<script>
var text = ""
var i = 0;
do {
text += "<br>The number is " + i;

14 © www.anuupdates.org Prepared by Dodda. Venkata Reddy M.Tech

Downloaded by Rajesh D ([email protected])


lOMoARcPSD|54064683

i++;
}while (i < 10);
document.getElementById("demo").innerHTML = text;
</script>
</body>
</html>

3. Jumping statements

The break statement "jumps out" of a loop. The continue statement "jumps over" one iteration in the loop.
The Break Statement
You have already seen the break statement used in an earlier chapter of this tutorial. It was used to "jump
out" of a switch() statement.
The break statement can also be used to jump out of a loop.
The break statement breaks the loop and continues executing the code after the loop (if any):
<!DOCTYPE html>
<html>
<body>
<p>A loop with a break.</p>
<p id="demo"></p>
<script>
var text = "";
var i;
for (i = 0; i < 10; i++) {
if (i === 3)
{
break;
}
text += "The number is " + i + "<br>";
}
document.getElementById("demo").innerHTML = text;
</script>
</body>
</html>

The Continue Statement


The continue statement breaks one iteration (in the loop), if a specified condition occurs, and continues
with the next iteration in the loop.
This example skips the value of 3:
<!DOCTYPE html>
<html>
<body>
<p>A loop which will skip the step where i = 3.</p>
<p id="demo"></p>
<script>
var text = "";
var i;

15 © www.anuupdates.org Prepared by Dodda. Venkata Reddy M.Tech

Downloaded by Rajesh D ([email protected])


lOMoARcPSD|54064683

for (i = 0; i < 10; i++) {


if (i === 3)
{
continue;
}
text += "The number is " + i + "<br>";
}
document.getElementById("demo").innerHTML = text;
</script>
</body>
</html>
4. eval(): This is very useful JavaScript built in function. String version of mathematical expressions can be
passed into the function where they are evaluated and the results returned as an integer.
Example: eval(“2+3/4-7+2);
……………..

8. Operators in JavaScript:

9. Arrays in JavaScript

An array is an ordered set of data elements which can be accessed through a single name. Like other
languages arrays in JavaScript store group of elements but of different types. In JavaScript an array is an
object and you have different methods for performing different operations.
There is no relationship in between the elements which are stored in JavaScript arrays. Then we can define
an array in JavaScript is a collection of non-homogenous elements under a single name. The index value
or the subscript value is used to perform any operations on an array. The for loop is most frequently used
loop along with arrays.

Basic array functions

The basic operations that are performed on arrays are creation, adding of elements, accessing individual
elements, searching an array, removing array elements.

a) Creating arrays:

1. Using an array literal is the easiest way to create a JavaScript Array.


Syntax:
var array_name = [item1, item2, ...];
Example:
var cars = ["Saab", "Volvo", "BMW"];
2. An array can also be created using the keyword “new”
var cars = new Array ("Saab", "Volvo", "BMW");
4. An array object to hold four elements can be created as
Var days=new Array [4];
5. An array can hold mixed data types
Var data = new Array (“Monday”, 34, 76.34,”Wednesday);

16 © www.anuupdates.org Prepared by Dodda. Venkata Reddy M.Tech

Downloaded by Rajesh D ([email protected])


lOMoARcPSD|54064683

b) Adding elements to an array


Array elements are accessed by their index. Adding an element uses the square bracket.

Var data [3] =”Thursday”;

When we add an element to the already filled array, the interpreter simply extend the array and inserts
the new item.

c) Accessing array members

The elements in the array are accessed through their index. The same access method is used to find the
elements and to change their value. When accessing array elements you don’t want to read beyond its
end. Therefore, you need to know how many elements have been stored. This is done through the length
attribute.
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Arrays</h2>
<p>JavaScript array elements are accessed using numeric indexes (starting from 0).</p>
<p id="demo"></p>
<script>
var cars = ["Saab", "Volvo", "BMW"];
document.getElementById("demo").innerHTML = cars;
</script>
</body>
</html>

d) Searching an array.
To search an array, simply read each element in turn and compare it with the value that you are looking
for. The following snapshot code shows how to search an array.
for(var i-0;i<length;i++)
{
If(data[i]=”Tuesday”)
{
document. Writeln (data[i]+”,”);
break;
}
}
e) Removing an array element
Removing elements from an array is quite string forward. JavaScript does not provide a built in function
to do this for you. To remove an element for yourself use the following procedure.
 Read each element in the array
 If the element is not the one you want to delete, copy it into a temporary array.
 If you want to delete the element do nothing.
 Increment the loop counter.
 Repeat the process.

17 © www.anuupdates.org Prepared by Dodda. Venkata Reddy M.Tech

Downloaded by Rajesh D ([email protected])


lOMoARcPSD|54064683

<html>
<head>
<title> removing an element </title>
</head>
<Script type=”text/JavaScript”>
<!-------------
document.writeln(“<h1> removing an element from array</h1>);
var data=[“monda”,” Tuesday”,34,76.46,”Wednesday”];
document.writeln(“<p>”);
var len=data.length;
for(i=0;i<len;i++)
{
document.writeln(data[i]+”,”);
}
document.writeln(“</p>”);
var rem=window.prompt(“which element you want to remove”);
var tem=new Array(data.length-1);
var j=0;
for(i=0;i<n;i++)
{
if(data[i]=rem)
{
// nothing to do
}
else
{
temp[j]=data[i];
j++;
}
}
data=temp;
var len=data.length;
for(var i=0;i<length;i++)
{
document.writeln(data[i]+”,”);
}
//-------->
</script>
</body>
</head>

18 © www.anuupdates.org Prepared by Dodda. Venkata Reddy M.Tech

Downloaded by Rajesh D ([email protected])


lOMoARcPSD|54064683

f) Object Based Arrays


In JavaScript arrays are object, if you want to perform any operation on arrays, simple specify its name
followed by dot operator and then followed by function name.
arrayName.function(parameter1,parameter2);
The following are the sum functions which are used to operate on arrays
1. concat (array1,array2): This function is used to add a list of elements at the end of another array.
a[]={1,2,3,4}’
b[]={5,6,7,8};
a.concat(b);
In the above code the array be is added at the end of ‘a’ and the newly created array is stored in ‘a’ as
a[]={1,2,3,4,5,6,7,8};
2. join(string): This function is used to join all the elements of an array as a string
a[]={‘h’,’e’,’l’,’l’,’o’}
join(a);

3. pop(): This method is used to delete an element from the array and it reduces size of array.
4. push(element1,element2): add a list of items to an array and it increases the size of the array.
5. reverse(): It reversers all the elements in the array, so that it follows last in first out process.
6. shift(): Remove one element from the array and it is the first element of an array.
7. slice(start, finish): It is used to extract a range of elements from an array from the start of index to finish
of the index. It works similarly as substr().
8.sort(): the array elements are sorted in index order.
9. slice(index,element1,element2,…..): It removes specified element in the array index and all the
remaining elements can form new array.
10. shift():The shift() method removes the first array element and "shifts" all other elements to a lower
index.
11. unshift(): The unshift() method adds a new element to an array (at the beginning), and "unshifts" older
elements.

------------------
10. Functions in JavaScript
A JavaScript function is a block of code designed to perform a particular task. A JavaScript function is
executed when "something" invokes it (calls it). JavaScript has a lot of built in functions into the language.
a) Defining functions
you can create your own function using the following syntax

function name(parameter1, parameter2, parameter3)


{
// code to be executed
}

 Function parameters are listed inside the parentheses () in the function definition.
 Function arguments are the values received by the function when it is invoked.
 Inside the function, the arguments (the parameters) behave as local variables.

19 © www.anuupdates.org Prepared by Dodda. Venkata Reddy M.Tech

Downloaded by Rajesh D ([email protected])


lOMoARcPSD|54064683

Advantages:
 Function reduces the complexity of the program
 The repeated code is eliminated by using function call
 Functions are basic building blocks of any programming language.

b) Passing parameters
Not every function accepts parameters, not all values have to be passed as parameters. When a
function receives a value as parameter, the value is given a name and can be accessed using that name by
the function. The names of parameters are taken from the function definition and are applied in the order
in which parameters are passed in.
<html>
<body>
<h2>JavaScript Functions</h2>
<p>This example calls a function which performs a calculation and returns the result:</p>

<script>
var x = myFunction(4, 3); // function call
document.writeln(x);
function myFunction(a, b)
{
return a * b;
}
</script>

</body>
</html>

Output:
Javascript Functions
This example calls a function which performs a calculation and returns the result:
12

c) Examining the function call


In JavaScript parameters are passed as arrays. Every function has two properties that can be used to
find information about the parameters.
function.arguments
This is the array of parameters that have been passed
function.arguments.length
This is the number of parameters that have been passed into the function.
Example:
var x = [ 'p0', 'p1', 'p2' ];
call_me(x);
function call_me(params) {
for (i=0; i<params.length; i++) {
alert(params[i])
}
}
20 © www.anuupdates.org Prepared by Dodda. Venkata Reddy M.Tech

Downloaded by Rajesh D ([email protected])


lOMoARcPSD|54064683

d) Returning values
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":
<html>
<body>
<h2>JavaScript Functions</h2>
<p>This example calls a function which performs a calculation and returns the result:</p>
<script>
var x = myFunction(4, 3); // function call
document.writeln(x);
function myFunction(a, b)
{
return a * b;
}
</script>
</body>
</html
e) Scoping Rules
A scope rule determines how a variable can be accessed. JavaScript variables can be either local or global.
global scope: global scope means that a variable is available to all parts of the program. such variables are
declared outside of any function and are usually used to hold static data that we won’t alter once it has
been created.
local scoping: local variables are declared inside a function. They can only be used by that function. If you
want the value associated with a local variable to the available to other functions then you must pass it as
parameter.
<html>
<body>
<h2>JavaScript Functions</h2>
<p>Outside myFunction() carName is undefined.</p>
<p id="demo1"></p>
<p id="demo2"></p>
<script>
myFunction();

function myFunction() {
var carName = "Volvo";
document.getElementById("demo1").innerHTML =
typeof carName + " " + carName;
}

document.getElementById("demo2").innerHTML =
typeof carName;
</script>
</body>
</html

21 © www.anuupdates.org Prepared by Dodda. Venkata Reddy M.Tech

Downloaded by Rajesh D ([email protected])


lOMoARcPSD|54064683

Objects in JavaScript

Data and objects in JavaScript, regular expressions, exception handling, built-in objects, events.
………………………………………………………………………………………………………………………….

1. Data and objects in JavaScript

An object is a thing. It can be anything that you like from. Some data through a set of methods to an
entire system. The reason that object orientation is such a powerful idea is that quite simply it lets software
designer and developers mimic the real world designs.

Objects are described in software and design constructs called classes. A class usually contains some data
items and some methods. Each class provides services to other classes in the system. A single generic class
can be specialized in many ways and each of the specialized versions inherits. Some of the properties and
behaves of the generic class. That means that common parts of the program can be developed just once
and easily reused.

An object is a run time instance of a class. The object has all of the behavior that was defined in the class
and is able to perform processing.

JavaScript Objects: The built in JavaScript objects such as document and window act, and are used, like
standard OO object. JavaScript diverges from traditional OO is in its treatment of user defined objects. An
object is really a data structure that has been associated with some functions. It doesn’t have inheritance
and the structure of the code can look a little peculiar.

<html>
<head>
<script language=”JavaScript”>
<!..........
function objDemo()
{
popup(“Hello”);
myhouse =new house(“ Dream hone”,2,4);
alert(“myhouse.name+”has”+myhouse.floors+”floors and”+myhouse.rooms()+”Rooms”);
myhouse.leave(“farewell”);
}

function house(name, floors, beds)


{
this.name=name;
this.floors=floors;
this.bedrooms=beds;
this.rooms=frrooms;
this.leave=popup;
}

22 © www.anuupdates.org Prepared by Dodda. Venkata Reddy M.Tech

Downloaded by Rajesh D ([email protected])


lOMoARcPSD|54064683

function frooms()
{

var groundfloor=3;
var utilities=2;
var total=0;
if(this.floors<=0)
{
total=0;
}
else
{
if(this.floors==1)
{
total = this.bedrooms+utilities;
}
else
{
total=(this.floors*utilities);
total+=groundfoloor;
total+=this.bedrooms;
}
}
return total;
}

function popup(msg)
{

alert(msg);
}
//----->
</script>
</head>
<body onLoad==objDemo”>
</body>
</html>

New Keyword: The new keyword is used to create objects. It allocates memory and storage for them and
sets all variables that can be set at this stage.

This keyword: to differentiate between global variables and those which are part of an object but may
have same name, JavaScript uses this keyword. Whenever you refer to a variable which is a part of an
object you must precede the variable name by this keyword.

.(dot) operator: when referring to a property of an object, where a method or a variable, a dot is placed
between the object name and the property.

23 © www.anuupdates.org Prepared by Dodda. Venkata Reddy M.Tech

Downloaded by Rajesh D ([email protected])


lOMoARcPSD|54064683

2. Regular Expressions in JavaScript

A regular expression is an object that describes a pattern of characters.

Regular expressions are used to perform pattern-matching and "search-and-replace" functions on text.

1. Creating Regular Expression

Syntax:

/pattern/modifiers;

Example:

var patt = /w3schools/i

In the above example

 /w3schools/i is a regular expression.


 w3schools is a pattern (to be used in a search).
 i is a modifier (modifies the search to be case-insensitive).

 A regular expression is a sequence of characters that forms a search pattern.

 When you search for data in a text, you can use this search pattern to describe what you are
searching for.

 A regular expression can be a single character, or a more complicated pattern.

 Regular expressions can be used to perform all types of text search and texts replace operations.

Dynamic patterns are created using new keyword to create an instance of the RegExp class;

RegExp = new RegExp(“/w3schools/i”);

24 © www.anuupdates.org Prepared by Dodda. Venkata Reddy M.Tech

Downloaded by Rajesh D ([email protected])


lOMoARcPSD|54064683

2. JavaScript Regular Expression Grammar

i) RegExp object methods

Method Descript
Compile() Changes the regular expression
Exec() Search a string for specified value.
Test() Search a string for s specified value.

ii) String Object methods that support Regular Expressions

Method Description
Search() Search a string for specified value. Returns the position of the value
Match() Search a string for a specified value. Returns an array of the found values.
Replace() Replace characters with other characters
Split() Split a string into an array of strings

iii) RegExp modifiers / flags

Modifier Description
i Performs case sensitive matching
g Performs a global matching. Find all matches, do not stop after the first match.
m Perform multiline matching.

iv)Regular Expression Patterns

Brackets are used to find a range of characters:

Expression Description
[abc] Find any of the characters between the brackets
[0-9] Find any of the digits between the brackets
(x|y) Find any of the alternatives separated with |

Metacharacters are characters with a special meaning:


Metacharacter Description
\d Find a digit
\s Find a whitespace character
\b Find a match at the beginning or at the end of a word
\uxxxx Find the Unicode character specified by the hexadecimal number xxxx

Example:
<html>
<head>
<title> pattern matching </title>
</head>

25 © www.anuupdates.org Prepared by Dodda. Venkata Reddy M.Tech

Downloaded by Rajesh D ([email protected])


lOMoARcPSD|54064683

<body>
<script language=”JavaScript”>
<!--------
var msg=prompt(“ enter the text”,” “);
var hunt=prompt(“enter regular expression”, “”);
var re=new RegExp(hunt);
var result=re.exec(msg);
document.writeln(“<h1> search result</h1><p>”);
if(result)
{
document.write(“ found”,+result[0]);
}
else
{
document.write(“not found”);
}
documtn.writeln(“</p>”);
document.close();
//--->
</script>
</body>
</html>

3. Exception Handling in JavaScript

There are three types of errors in programming:


(a) Syntax Errors
(b) Runtime Errors, and
(c) Logical Errors.

Run time error handling is very important in all programs. Your program should never fall over or stop
just because a user enters invalid data or does something unexpected. May object oriented programming
languages provide a mechanism for dealing with general classes of errors. This mechanism is called
exception handling.
An exception is an object based programming object, created dynamically at run time which encapsulates
an error and some information about it.

The latest versions of JavaScript added exception handling capabilities. JavaScript implements the
try...catch...finally construct as well as the throw operator to handle exceptions.
 The try statement lets you test a block of code for errors.
 The catch statement lets you handle the error.
 The throw statement lets you create custom errors.
 The finally statement lets you execute code, after try and catch, regardless of the result.

26 © www.anuupdates.org Prepared by Dodda. Venkata Reddy M.Tech

Downloaded by Rajesh D ([email protected])


lOMoARcPSD|54064683

Example:
<html>
<head>
<script type = "text/javascript">
<!--
function myFunc() {
var a = 100;
var b = 0;

try {
if ( b == 0 ) {
throw( "Divide by zero error." );
} else {
var c = a / b;
}
}
catch ( e ) {
alert("Error: " + e );
}
}
//-->
</script>
</head>
<body>
<p>Click the following to see the result:</p>
<form>
<input type = "button" value = "Click Me" onclick = "myFunc();" />
</form>
</body>
</html>

4. Event Handling JavaScript


 HTML events are "things" that happen to HTML elements.
 When JavaScript is used in HTML pages, JavaScript can "react" on these events.

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.

27 © www.anuupdates.org Prepared by Dodda. Venkata Reddy M.Tech

Downloaded by Rajesh D ([email protected])


lOMoARcPSD|54064683

Example
<!DOCTYPE html>
<html>
<body>
<button onclick="document.getElementById('demo').innerHTML=Date()">The time is?</button>
<p id="demo"></p>
</body>
</html>
JavaScript is an event driven system

JavaScript is an event driven system. Nothing happens unless it is initiated by an event outside the script.
An event is any change that the user makes to the state of the browser. Our script can be initiated when
the page loads and then run automatically. Generally we add a script to a page to improve its
functionality or appearance. The script is an integral part of the page but its operation should always be
controlled by the user.
Examples of using JavaScript to react to events

Common HTML Events

Here is a list of some common HTML events:


Event Description
onchange An HTML element has been changed
onclick The user clicks an HTML element
onmouseover The user moves the mouse over an HTML element
onmouseout The user moves the mouse away from an HTML element
onkeydown The user pushes a keyboard key
onload The browser has finished loading the page

Example JavaScript for OnLoad


<!DOCTYPE html>
<html>
<head>
<script>
function myFunction() {
alert("Page is loaded");
}
</script>
</head>
<body onload="myFunction()">
<h2>Hello World!</h2>
</body>
</html>

28 © www.anuupdates.org Prepared by Dodda. Venkata Reddy M.Tech

Downloaded by Rajesh D ([email protected])


lOMoARcPSD|54064683

5. Objects in JavaScript / Built in Objects in JavaScript


1. The document object:

A document is a web page that is being either displayed or created. The document has a number of
properties that can be accessed by JavaScript programs and used to manipulate the content of the page.
Write or writeln Html pages can be created using JavaScript. This is done by using the write or writeln
methods of the document object.
Document.write(“<h1> Hello </h1>”);

2. The form object:

Two aspects of the form can be manipulated through JavaScript. First, most commonly and probably most
usefully, the data that is entered onto your form can be checked at submission. Second you can actually
build forms through JavaScript.
<html>
<head>
<script language="javascript">
function fibbo()
{ var a=0,b=1,c,i=1;
var op=a+" ,"+b+" ,";
var num=window.prompt("Enter the Number:",1);
for(i=1;i<=num;i++)
{
c=a+b;
a=b;
b=c;
op+=c+" ,";
}
document.getElementById("num").innerHTML="Series is "+op;
}
</script>
</head>
<body>
<form name="f1">
<table border=2>
<tr>
<td>
<input type=button value="Fibonacci" onclick="fibbo()">
</td>
<td id="num">result</td>
</tr>
</table>
</form>
</body>
</html>

29 © www.anuupdates.org Prepared by Dodda. Venkata Reddy M.Tech

Downloaded by Rajesh D ([email protected])


lOMoARcPSD|54064683

3. The browser Object

No two browsers models will process your script in the same way. It is important that you try to find out
which browser is being used to view your page. You can then make a choice for your visitors.

Some of the properties of the browser object is as follows


 Navigator.appCodeName: The internal name for the browser.
 Navigator.appVersion: This is the public name of the browser.
 Navigator.appVersion: The version number, platform on which the browser is running.
 Navigator.userAgent: The strings appCodeName and appVersion concatenated together.
4. Date Object:
JavaScript provides functions to perform many different date manipulations.
Some of the functions are mentioned below.
 Date( ): Construct an empty date object.
 Date(year, month, day [,hour, minute, second]): Create a new Date object based upon
Numerical values for the year, month and day. Optional time values may also be supplied.
 getDate( ): Return the day of the month
 getDay( ): Return an integer representing the day of the week.
 getFullYear( ): Return the year as a four digit number.
 getHours( ): Return the hour field of the Date object.
 getMinutes( ): Return the minutes field of the Date object.
 getSeconds( ): Return the second field of the Date object.
 setDate(day ): Set the day value of the object. Accepts values in the range 1 to 31.
 setFullYear( year [,month, day]): Set the year value of the object. Optionally also sets month and
day values.
 toString( ): Returns the Date as a string.

5. String Object
6. Math Object

30 © www.anuupdates.org Prepared by Dodda. Venkata Reddy M.Tech

Downloaded by Rajesh D ([email protected])

You might also like