Ad Code

Responsive Advertisement

JavaScript

 

UNIT- III

JAVASCRIPT

1.What is the DHTML?

Dynamic HTML is not really a new specification of HTML, but rather a new way of looking at and controlling the standard HTML codes and commands.

            When thinking of Dynamic HTML, you need to remember the qualities of standard HTML, especially that once a page is loaded from  the server, it will not change until another request comes to the server. Dynamic HTML give more control over HTML elements and allows them to change at any time, without returning to the Web Server.

There are four parts to DHTML.

  1. HTML
  2. Document Object Model (DOM)
  3. Scripts
  4. Cascading Style Sheets

1. HTML: HTML Stands for Hyper Text Markup Language. It is a method of describing the format of a documents which allows them to viewed on computer screens. HTML documents are displayed by web browsers programs which can navigate across networks and display a wide variety of information. HTML pages can be developed to be simple text or to be complex multimedia containing sound, moving images, and many more.

2. DOM: The DOM is one, which allows you to access any part of your web page to change it with DHTML. Every part of a web page is specified by the DOM and using its consistent naming conventions you can access them and change their properties.

3. Scripts: Scripts written in either JavaScript or VBScript are the two most common scripting languages used to activate DHTML. You use a scripting language to control the objects specified in the DOM.

4. Cascading Style Sheets: CSS is used in DHTML to control the look and feel of the web page. Style sheets define the colors and fonts of text, the background colors and images, and the placement of objects on the page. Using scripting and the DOM, you can change the style of various elements.

Features of DHTML

  1. Changing the tags and properties.
  2. Real-time positioning.
  3. Dynamic fonts.
  4. Data binding.

 

2.What are the Differences between HTML and DHTML.

HTML

DHTML

Hyper Text Markup Language

Dynamic Hyper Text Markup Language

Used to create Static web pages.

Used to create dynamic web pages.

Contains Tags for formatting text.

Combination of HTML tags, CSS and Scripting language.

Simple and less interactive.

Complex and great interactive.

Navigation using Links.

Navigation thru menus.

Images used for display purpose only.

Images used for presentation, for simple animations, etc.

Contents changed when page is reloaded.

Contents changed without reloading the entire web page.

Tags are not case sensitive.

Case sensitive due to scripting.

 

3. What is JavaScript? Explain the features of JavaScript?

            We cannot create the interactive web pages using HTML. Hence JavaScript is designed to add the interactivity in the HTML pages. The JavaScript is very much similar to a programming language. JavaScript originates from a language called Live Script. JavaScript is platform independent and can be run everywhere. JavaScript is used for client side programming.

                        JavaScript was originally developed by Netscape Corporation for use in its browser, Netscape Navigator. It includes a convenient syntax, flexible variable types, and easy access to the browser’s features. It can run on the browser without being compiled, the source code can be placed directly into a web page.

JavaScript gives web developers a programming language for use in web pages and allows them to do:

Ø  Read elements from documents and write new elements and text into documents.

Ø  Manipulate or move text.

Ø  Create pop-up windows.

Ø  Perform mathematical calculations on data.

Ø  Read to events, such as user rolling over an image or clicking a button.

Ø  Retrieve the current date and time from user’s computer.

Ø  Determine the user’s screen size, browser version or screen resolution.

Ø  Perform actions based on conditions such as alerting users, if they enter the wrong information into a form or if they press a certain button.

Benefits of JavaScript :

          JavaScript has a number of big benefits to anyone who wants to make their Website dynamic.

    F  It is widely supported in Web browsers

    F  It gives easy access to the document objects and can manipulate most of them.

    F  JavaScript can give interesting animations without the long download times associated with many multimedia data types.

    F  Web surfers don't need a special plug-in to use your scripts.

    F  JavaScript is relatively secure.

    F  JavaScript can read neither from your local hard disk drive nor write to it.

    F  We cannot get a virus infection directly from JavaScript.

Limitations of JavaScript :

Although JavaScript looks to much advantageous, but it has some Limitations also:

    F  Most scripts rely upon manipulating the elements of the DOM. Support for a standard set of objects currently doesn't exist and access to objects differ from browser to browser.

    F  If your script doesn't work then your page is useless

    F  The problems of broken scripts many web surfers disable JavaScript support in their browser.

    F  Scripts can run slowly and complex scripts can take a long time to start up.

Syntax:

<script language=”javascript”>

. . .

</script>

 

4. Explain various data types in JavaScript?

            Programming languages usually have several different types of data. Commonly use characters, integers (whole numbers), Booleans (logical values of true and false), strings (ordered set of characters), reals (complex numbers) and many others besides. JavaScript has only four types of data:

Numeric: These are basic numbers. They can be integers such as 1, 23, 123 or floating point values like 23.42, -56.01, and 2E45. We need to differentiate between them as we declare and use them and can merely change the type of data which a variable holds as the program runs.

 

Strings: These are collection of characters that are not numbers. The value of string can even contain spaces and may be totally made from digits. When a string value is assigned to a variable we must specify in quotes. We can also use nested quotes by placing a \ before the inner quotes.

            Ex:       visitor_name = “ravi”;

                        visitor_add = “gnagar, \’vijayawada\’”;

Boolean: Boolean variables hold the values true and false. These are used a lot in programming to hold the result of conditional tests.

Null: A null value means one that has not yet been decided. It does not mean nil or zero and should not be used in that way-ever.

5. What is variable? How to work with variables in JavaScript?

Variables: The variables are created in order to store some information. This information can be string or it can be numeric.

 Like other programming languages, JavaScript has variables. A variable is a named value that you use in our programs. Variables can be given different values throughout the JavaScript program. Each variable has a name. It can also be called as an identifier. While choosing a variable name certain rules must be followed:

            F        Names should begin with a letter, a digit or the underscore

            F        We cannot use spaces in names

            F        Names are case-sensitive

            F        We cannot use a reserved word as a variable name.

            F        Name of the variable can be of any length

Program

<html>

<head>

<title> Variables in JavaScript</title>

</head>

<center>

<script type="text/javascript">

var a, b, c;

var str;

a = 2;

b = 3;

c = a + b;

str ="The Result =";

document.write("Performing addition of 2 and 3.<br>");

document.write(str);

document.write(c);

</script>

</center>

</body>

</html>

 

6. Explain the Operators in JavaScript.

Assignment operator: The assignment operator = is used to assign values to JavaScript variables.

Example:

y=5;                 x=y+z;

Arithmetic Operators: Arithmetic operators are used to perform arithmetic between variables and/or values.

Given that y=5, the table below explains the arithmetic operators:

Operator

Description

Example

Result

+

Addition

x=y+2

x=7

-

Subtraction

x=y-2

x=3

*

Multiplication

x=y*2

x=10

/

Division

x=y/2

x=2.5

%

Modulus (division remainder)

x=y%2

x=1

++

Increment

x=++y

x=6

--

Decrement

x=--y

x=4

 

Comparison Operators: Comparison operators are used in logical statements to determine equality or difference between variables or values. Given that x=5, the table below explains the comparison operators:

Operator

Description

Example

= =

is equal to

x==8 is false

= = =

is exactly equal to (value and type)

x= = =5 is true
x= = ="5" is false

!=

is not equal

x!=8 is true

> 

is greater than

x>8 is false

< 

is less than

x<8 is true

>=

is greater than or equal to

x>=8 is false

<=

is less than or equal to

x<=8 is true

 

Logical Operators: Logical operators are used to determine the logic between variables or values. Given that x=6 and y=3, the table below explains the logical operators:

Operator

Description

Example

&&

and

(x < 10 && y > 1) is true

||

or

(x==5 || y==5) is false

!

not

!(x==y) is true

 

Conditional Operator: JavaScript also contains a conditional operator that assigns a value to a variable based on some condition.

Syntax:  variablename=(condition)?value1:value2 

 

Example

c = (a>b) ? a : b;

It checks the condition a>b whether is true or not. If true, a value will be assigned to c, if it is false, b value will be assigned to c.

 

7. Explain the Control Structures in JavaScript.

Conditional statements are used to perform different actions based on different conditions.

  1. If Statement:

It is used to execute some code only if a specified condition is true.

Syntax

if (condition)

{

code to be executed if condition is true

}

Example

<script type="text/javascript">

var a = 10;

if (a<10)

{

document.write("<b> a is less than 10</b>");
}

</script>

  1. If...else Statement

Use the if....else statement to execute some code if a condition is true and another code if the condition is not true.

Syntax

if (condition)
{

code to be executed if condition is true
}
else
{

code to be executed if condition is not true
}

Example

<script type="text/javascript">

var a=10, b=5;

if (a>b)

{

document.write("a is big");

}

else

{

document.write("b is big");

}

</script>

  1. If...else if...else (Nested if) Statement

Use the if....else if...else statement to select one of several blocks of code to be executed.

Syntax

if (condition1)
{
            code to be executed if condition1 is true
}
else if (condition2)
{
            code to be executed if condition2 is true
}
else
{
            code to be executed if condition1 and condition2 are not true
}

Example

<script type="text/javascript">
var a=6, b=8, c=13;

if (a>b && a>c)
  {
  document.write("a is big");
  }
else if (b>c)
  {
  document.write("b is big");
  }
else
  {
  document.write("c is big");
  }
</script>

  1. Switch Statement

Use the switch statement to select one of many blocks of code to be executed.

Syntax

switch(n)
{
case 1:
            execute code block 1
            break;
case 2:
            execute code block 2
            break;
default:
            code to be executed if n is different from case 1 and 2
}

First we have a single expression n (most often a variable), that is evaluated once. The value of the expression is then compared with the values for each case in the structure. If there is a match, the block of code associated with that case is executed. Use break to prevent the code from running into the next case automatically.

Example

<script type="text/javascript">
var ch = prompt(“Enter your choice”, “0”);

var a=6,b=4;

switch (ch)
{
case 1:   document.write("sum = " + (a+b));

break;

case 2:   document.write("difference = " + (a-b));

break;

case 3:  document.write("product = " + (a*b));

break;
default: document.write("Invalid operation");
}
</script>

Iterative Statements:

Loops execute a block of code a specified number of times, or while a specified condition is true.

1. for Loop

The for loop is used when you know in advance how many times the script should run.

Syntax

for ( initialization ; condition; increment/decrement )
{

code to be executed
}

Example

<html>

<body>

<script type="text/javascript">

var i;

for (i=0;i<=5;i++)

{

document.write("The number is " + i);

document.write("<br />");

}

</script>
</body>
</html>

2. while Loop

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

 

Syntax

Initialization;

while (condition)
{
            code to be executed

increment
}

Example

<html>
<body>
<script type="text/javascript">
var i=1;
while (i<=5)
{
     document.write("The number is " + i);
     document.write("<br />");
     i++;
  }
</script>
</body>
</html>

3. do...while Loop

The do...while loop is a variant of the while loop. This loop will execute the block of code ONCE, and then it will repeat the loop as long as the specified condition is true.

Syntax

initialisation

do
{
            code to be executed

increment / decrement
}while (condition);

Example

<html>
<body>
<script type="text/javascript">
var i=0;
do
{
     document.write("The number is " + i);
     document.write("<br />");
     i++;
}while (i<=5);

 

</script>
</body>
</html>

Jump Control Statements:

The break Statement

The break statement will break the loop and continue executing the code that follows after the loop (if any).

Example

<html>
<body>
<script type="text/javascript">
var i=0;
for (i=0;i<=10;i++)
  {
  if (i==3)
    {
    break;
    }
  document.write("The number is " + i);
  document.write("<br />");
  }
</script>
</body>
</html>

The continue Statement

The continue statement will break the current loop and continue with the next value.

Example

<html>
<body>
<script type="text/javascript">
var i=0
for (i=0;i<=100;i++)
  {
  if (i%5==0)
    {
    continue;
    }
  document.write("The number is " + i);
  document.write("<br />");
  }
</script>
</body>
</html>

For...In Statement

The for...in statement loops through the elements of an array or through the properties of an object.

Syntax

for (variable in object)
  {
  code to be executed
  }

Note:

1) The code in the body of the for...in loop is executed once for each element/property.

2) The variable argument can be a named variable, an array element, or a property of an object.

Example

<html>
<body>
<script type="text/javascript">
var x;
var mycars = new Array();
mycars[0] = "Saab";
mycars[1] = "Volvo";
mycars[2] = "BMW";
for (x in mycars)
  {
  document.write(mycars[x] + "<br />");
  }
</script>
</body>
</html>

8.What is an Array? Explain how arrays managed in JavaScript? (or) Explain the Object based Array Functions in JavaScript.

Array

An array is an ordered set of data elements which can be accessed through a single variable name. Data elements can be accessed either sequentially by reading from the start of the array, or by their index. The index is the position of the element in the array with the first element being at position 0 and the last at arraylength – 1.

Creating Arrays:

Syntax 1:

var days = [“Monday”, “Tuesday”, “Wednesday”, “Thursday”];

 

That creates an array of four elements, each holding a text string. An array of elements is surrounded by square brackets.

Syntax 2:

var days = new Array(“Monday”, “Tuesday”, “Wednesday”, “Thursday” );

Using this construct, the contents of the array are surrounded by parentheses because they are parameters to the constructor of the Array object.

Syntax 3:

var days = new Array(4);

JavaScript arrays can hold mixed data types as the follows:

var data = [“Monday”, “Tuesday”, 34, 76.34, “Wednesday”];

Adding elements to an Array:

Array elements are accessed by their index. The index denotes the position of the element in the array and start from 0.

            var days[3] = “Monday”;

            data[5] = “Thursday”;

Accessing Array Elements:

The elements in the array are accessed through their index. The same access method is used to find and to change their value.

length: This property returns the number of elements stored in the array. Remember that index numbers run from 0 to length-1.

Object based  Array functions:

Actually a JavaScript array is an object. Each of the array functions is used by specifying the name of the array followed by a dot and then the name of the function.

Syntax:

arrayname.function( parameter1, parameter2, … );

1.concat(): A list of arrays is concatenated onto the end of the array and a new array returned. The original arrays are all unaltered by this process.

Syntax:

arrayname.concat( array2, array 3, array 4, …  );

Example:

var first = [“Monday”, “Tuesday”];

var second = [“Wednesday”, “Thursday”];

var third = [“Friday”, “Saturday”];

var result = first.concat(second, third);

2.join(): It passes through the array creating a string of all elements. In the resulting string the elements are separated using the optional string parameter. If parameter is omitted the elements are separated using comma.

Syntax:

arrayname.join(string);

Example:

var days = [“Monday”, “Tuesday”, “Wednesday”];

document.write( days.join(“ , “) );

3.pop(): This function removes the last element from the array and reduces the number of elements in the array by one.

Syntax:

arrayname.pop();

Example:

days.pop();

4.push(): Adds a list of items onto the end of the array. The items are separated using commas in the parameter list.

Syntax

arrayname.push( element-1 [, element-2, … , element-N] );

Example:

days.push(“Thursday”, “Friday”);

5.reverse(): As the name suggests, this function swaps all of the elements in the array so that which was first is last, and vice versa.

Syntax:

arrayname.reverse();

Example:

days.reverse();

6.shift():Removes the first element of the array and in so doing shortens its length by one.

Syntax:

arrayname.shift();

Example:

days.shift();

7.slice(): This function used to extract a range of elements from an array. Two parameters need to pass to this function. The first parameter specifies the starting position and the second parameter specifies the last number. If second parameter is omitted, it returns all the elements from the starting element. The original array is unaltered by this function.

Syntax:

arrayname.slice( start [ , finish ] );

Example:

var days = [“Monday”, “Tuesday”, “Wednesday”, “Thursday”, “Friday”];

var somedays = days.slice( 2, 4 );

8.sort(): The array is sorted into lexicographic, dictionary, order by using this function.

Syntax:

arrayname.sort();

Example:

days.sort();

Program 11:

<html>

<head>

<title> Array and object based Array functions</title>

</head>

 

<body>

<script language="javascript" type=”text/javascript”>

var data=["HTML","XHTML",1000,50.50];

var len=data.length;

document.writeln("Length:"+len);

data[5]="DHTML";

var len=data.length;

document.writeln("<br><br>New length:"+len);

document.writeln("<h1>Array Functions</h1>");

data.push("XML",66.55);

data.pop();

document.writeln("<br><br><br>push and pop:"+data.join(","));

data.shift();

data.unshift("GANESH");

document.writeln("<br><br><br>shift and unshift:"+data.join(","));

data.reverse();

document.writeln("<br><br><br>reverse:"+data.join(","));

data.sort();

document.writeln("<br><br><br>sort:"+data.join(","));

</script>

</body>

</html>

 

9. What is a Function? Explain about functions in JavaScript?

            A function is a piece of code that performs a specific task. By creating a function the same piece of code can be used repeatedly throughout the program. Once the function is created it can be used by calling the function. Until the program calls a function, that code won’t be do anything.

Defining Function

            User defined functions are named and or developed by the user. They are initially declared and coded, later they are called depending on the requirements. Functions are defined using the function keyword. The function name can be any combination of letters, digits and underscrore but not contain a space.

            function function_name( parameters )

            {

                        Code to be executed

            }

Parameter passing:

            When a function receives a value as a parameter, that 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.

Returning values:

            A function can return a value by using “return” statement.

Program 12:

<html>

   <head>

      <title> Example Program on JavaScript Functions </title>

      <script language="javascript">

            function fact()

            {

                   var f = 1, i, n;

                   n = prompt("Enter a number");

                   for(i=1; i<=n; i++)

                        f = f * i;

                   document.writeln("Factorial of given number is : " + f);

            }

      </script>

 

   </head>

   <body onLoad="fact()">

   </body>

</html>

10. Explain the string and mathematical functions in JavaScript.

String functions:

String manipulation involves either joining strings together, splitting them apart or searching through them. JavaScript has functions which perform all of those operations.

1:charAt:This function returns the character which is at position index in the string.

Syntax:  charAt(index)

Example:

var str = “welcome to javascript”;

str.charAt(2)

2.concat:This function concatenates the given comma separated strings and returns a new string.

Syntax:concat(“string” [, “string”,…])

Example:

var str1 = “welcome to ”;

var str2 = “javascript”;

var str3 = str1.concat(str2);

3.indexOf:      The string is searched for the string or quoted character in the first parameter. If the search is successful, the index of the start of the target string is returned otherwise it returns -1

Syntax: indexOf(“search”)

Example:

var str = “welcome to javascript”;

str.indexOf(‘e’)

4.lastIndexOf:This function does exactly the same thing as indexOf() but works its way backwards along the string. If the search is successful, the index of the start of the target string is returned otherwise it returns -1.

Syntax: lastIndexOf(“search”)

Example: str.lastIndexOf(‘e’)

5.length:Returns the value which holds the number of characters in the string.

Syntax:  length

Example:  str.length   returns 21.

6.split:The split() function breaks the string apart whenever it encounters the character passed in as the parameter. The pieces of the string are stored in an array.

Syntax:  split(separator)

Example:var s = str.split(“ “);

7.substr:This function returns a substring which starts at the character indicated by the index parameter. The substring continues either to the end of the string or for the number of characters indicated by the length parameter.

Syntax:  substr(index [, length])

Example: str.substr(3, 4)       returns “come”

8substring:Returns the set of characters which starts at index1 and continues upto, but does not include, the character at index2.

Syntax:  substring(index1[, index2])

Example: str.substring(3, 6) returns “come”

9.toLowerCase():Converts all characters in the string to lower case.

Syntax: toLowerCase():

Example:  str.toLowerCase()

 

10.toUpperCase():Converts all characters in the string to upper case.

Syntax: toUpperCase():

Example: str.toUpperCase()

 

Mathematical functions:

Mathematical functions and values are part of a builtin JavaScript object called Math. All functions and attributes used in complex mathematics must be accessed via this object.

1.abs:  Returns the absolute value the number passed into it.

Syntax: abs(value)

Ex: Math.abs(-10)

2.ceil: Returns the integer which is greater than or equal to the value passed in.

Syntax:  ceil(value)

Ex:  Math.ceil(2.3)

3.floor: Returns the largest integer which is smaller than, or equal to, the number passed in.

Syntax:  floor(value)

Ex:  Math.floor(2.8)

4.sqrt: Returns the square root of the value.

Syntax:  sqrt(value)

Ex:  Math.sqrt(25)

5.max: Returns the larger of its arguments.

Syntax:  max(value1, value2)

Ex:  Math.max(10, 20, 30)

6.min:  Returns the smaller of its arguments.

Syntax:  min(value1, value2)

Ex: Math.min(10,20,30)

7. pow: Returns the result of raising value to power.

Syntax:  pow(value, power)

Ex: Math. pow(5,3)

8.cos:  This function returns cosine value.

Sy: Math.cos(value)

9.sin: This function returns sine value

Sy:  Math.sin(value)

10.tan:  This function returns  tangent value.

Sy: Math.tan(value)

Program 13

<html>

<head><title>String & Mathematical Functions</title></head>

<body>

<script language="javascript">

document.writeln("<h1>String functions</h1> ");

var str="reliance";

document.writeln("<br>Lower Case:"+str.toLowerCase());

document.writeln("<br>Upper Case:"+str.toUpperCase());

document.writeln("<br>SubStr:"+str.substr(1,4));

document.writeln("<br>Sub String:"+str.substring(1,4));

document.writeln("<br>IndexOf:"+str.indexOf("i"));

document.writeln("<br>LastIndexOf:"+str.lastIndexOf("i"));

 

document.writeln("<h1>Mathematical functions</h1> ");

document.write("<br> Absolute " + Math.abs(-10) );

document.write("<br> Ceil " + Math.ceil(2.3));

document.write("<br> Floor " + Math.floor(2.8));

document.write("<br> max  " + Math.max(10,20,30));

document.write("<br> min  " + Math.min(10,20,30));

document.write("<br> pow " + Math.pow(5,3) );

document.write("<br> sqrt  " + Math.sqrt(25));

 

</script>

</body>

</html>

11. What is an Object? How JavaScript support Objects? (OR)

JavaScript is an Object Oriented Programming. Justify.

Ø  JavaScript is an Object Oriented Programming (OOP) language.

Ø  An OOP language allows you to define your own objects and make your own variable types.

Ø  An Object is a thing. It can be anything that you like from some data through a set of methods to an entire system.

Ø  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 behavior of the generic class.

Ø  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.

Ø  Generally objects don’t act independently. Their actions are triggered by events throughout the system.

Ø  Usually actions occur because an object in the system requests a service from another 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.

Keywords used with Objects:

new:

Ø  The keyword new is used to create objects.

Ø  It allocates memory and storage for them and sets all variables that can be set.

Ø  new calls a function which has the same name as the type of object that is being created. This function is called the “constructor”.

this:

Ø  To differentiate between global variables and those which are part of an object but may have the same name, JavaScript uses this.

Ø  The variable which is a part of an object must precede the variable name by this.

Ø  Separate the variable name from object with a dot.

. dot:

Ø  When referring to a property of an object, whether a method or a variable, a dot is placed between the object name and the property.

 

12. What is Regular Expression? Explain the creation of Regular Expression in JavaScript.

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

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

Ø  A simple pattern can be one single character.

Ø  A more complicated pattern can consist of more characters, and can be used for parsing, format checking, substitution and more.

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

Ø  JavaScript include a set of routines to manipulate strings and search patterns. These are wrapped up as regular expression objects.

Ø  JavaScript regular expressions are more than patterns: they include functions which you call from your scripts when need a pattern finding.

Creating Regular Expressions:

            A regular expression is a JavaScript object. As with any other type of object there are multiple ways of creating them. They can be created statically when the script is first parsed, or dynamically at run-time.

A static regular expression is created as follows:

            regex = “fish”;

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

            regex = new RegExp(“fish “);

Methods of RegExp object:

test(): The test() method searches a string for a specified value, and returns true or false, depending on the result.

Example

var patt1=new RegExp("a");

document.write(patt1.test("This is a pattern"));

Since there is an "a" in the string, the output of the code above will be: true

 

exec(): The exec() method searches a string for a specified value, and returns the text of the found value. If no match is found, it returns null.

Example

var patt1=new RegExp("a");

document.write(patt1.exec("This is a pattern"));

Since there is an "a" in the string, the output of the code above will be: a

 

The following table narrates the regular expression grammar applied while using the symbolic templates in JavaScript.

Token

Description

^

Match at the start of the input string.

$

Match at the end of the input string.

*

Match 0 or more times.

+

Match 1 or more times.

\d

Match a digit.

\w

Match any alphanumeric character or the underscrore.

Program

<html>

   <head>

      <title> Pattern Matching </title>

      <script language="javascript">

            var msg = prompt("Enter a test string : ");

            var str = prompt("Enter a regular expression : ");

            var re = new RegExp(str);

            var result = re.exec(msg);

            document.writeln("<h2> Search Results </h2>");

            if( result )

                 document.write(" Found : " + result[0] );

            else

                 document.write("Not found");

      </script>

   </head>

   <body>

   </body>

</html>

 

13. Explain Exception Handling in JavaScript with an example.

            One of the most fascinating features of object oriented programming languages is “Exception Handling”. In programming aspects “exceptions” refers to run-time errors. Using this concept the errors which may occur during run-time of a given program can be successfully handled, hence the name of the concept.

 

            In terms of object oriented construct, exceptions are taken upon as an object which gets dynamically framed as the code executes. The object accumulates all the errors and also its relative information. Object oriented programming languages privileges users to define separate exception classes which may encompass all the expected exception hence providing fertility to the programming disciplines.

 

            In order to handle the exceptions, we usually report to two important constructs i.e., try … catch and throw respectively.

 

try … catch

            It is a block where you have code which might cause the creation of an exception. If an exception is thrown by any statements, execution of the whole block ceases and the program looks for a catch statement to handle the exception. The try…catch block takes the form:

 

            try

            {

                        Statements

            }

            catch (exception )

            {

                        Statements to handle exception

            }

 

throw

            As an exception is an object, it is created using the standard new method. Once the exception object exists, we should throw the exception, until there’s a piece of code which can handle it. The syntax of the throw is:

            Do something

            If an error happens

            {

                        Create a new exception object

                        throw the exception

            }

try…catch..finally Statement

JavaScript has a finally statement that can be used as an optional construct along with try..catch statements. When the finally statement is placed in a try…catch construct, it always runs following the try…catch structure.

 

Program

<html>
   <head>
      <script type="text/javascript">
        try
        {
           document.write(junkVariable)
        }

        catch(err)
        {
           document.write(err.message + "<br/>")
        }
        finally
        {
           document.write("Finally Block entered: Welcome")
        }
      </script>
   </head>
<body>
   </body>

</html>

 

14. Explain the Built-in Objects in JavaScript.

Document Object

            A document is a Webpage that is being either displayed or created. Each HTML document loaded into a browser window becomes a Document object. The Document object provides access to all HTML elements in a page, from within a script. The document has a number of properties that can be accessed by JavaScript programs and used to manipulate the content of the page. The Document object is also part of the Window object, and can be accessed through the window.document property.

write() Writes HTML expressions or JavaScript code to a document.

writeln() Same as write(), but adds a newline character after each statement

anchors: Any name point inside an HTML document is an anchor. Anchors are created using <a name = … >. The anchors property is an array of these names in the order in which they appear in the HTML document. Anchors can be accessed like this:     document.anchors[0];

links: Another array holding potentially useful information about the page. All links are stored in an array in the same order as they appear on the web page.

Forms: Again this is an array in the order of the document. This one contains all of the HTML forms. By combining this array with the individual form objects each from item can be accessed.

 

Window Object

            The browser window is a mutable object that can be addressed by JavaScript. The properties and methods of Window object are:

open(“URL”, “name”): This opens a new document which contains the document specified by URL. The window is given an identifying name so that it can be manipulated individually.

close(): This shuts the current window.

Many of the attributes of a browser are undesirable in a pop-up window. They can be switched on and off individually.

toolbar = [ 1 / 0 ]

status = [ 1 / 0 ]

scrollbars = [ 1 / 0 ]

resizable = [ 1 / 0 ]

width = pixels

height = pixels

Program

<html>

<head>

            <title> Opening a New Window </title>

<script type="text/javascript">

function open_win()

{

window.open("HTML.doc","_blank", "toolbar=yes,

location=yes, directories=no, status=no, menubar=yes,

scrollbars=yes, resizable=no, width=400, height=400");

}

</script>

</head>

</body>

</body>

</html>

 

Form object

            Two aspects of the form can be manipulated though JavaScript. First, most commonly and probably most usefully the data that is entered onto the form can be checked at submission. Second, we can actually build forms through JavaScript.

            The elements of the form are held in an array. This means that any of the properties of those elements that can set using HTML code can be accessed though JavaScript.

onClick=”method”

            This method can be applied to all form elements. The event is triggered when the user clicks on that element.

onSubmit=”method”

            This event can only be triggered by the form itself and occurs when a form is submitted.

onReset=”method”

            This is a form-only event and triggered when a form is reset by the user.

 

Browser Object

            No two browser models will process the JavaScript in the same way. It is important that find out which browser is being used to view the page, so that make a choice for visitors such as:

·         Exclude browsers that are unable to use code;

·         Redirect them to a non-scripted version of site;

·         Present scripts that are tailored to suit each browser.

The browser is a JavaScript object and can be queried from within code. The browser object is actually called the navigator object. The following are the some properties:

navigator.appCodeName

            The internal name for the browser. For both major products this is Mozilla, which was the name of the original Netscape code source.

navigator.appName

            This is the public name of the browser – navigator or Internet Explorer for the big two.

navigator.appVersion

            The version number, platform on which the browser is running, and (for Internet Explorer) the version of navigator with which it is compatible.

navigator.plugins: An array containing details of all installed plug-ins.

navigator.mimeTypes: An array of all supported MIME types – useful if need to make sure that the browser can handle data.

Program

<html>

    <head>

        <script language="javascript">

document.write("<br> <b> appcode name : </b>" + navigator.appCodeName);

document.write(" <br> <br> <b> app name : </b>" + navigator.appName);

document.write(" <br> <br> <b> version : </b>" + navigator.appVersion);

document.write(" <br> <br> <b> user agent : </b>" + navigator.userAgent);

document.write("<br> <b> mime type : </b>" + navigator.mimeTypes.length);

document.write(" <br> <br> <b> mime types : </b> <br>" );

for(i=0; i<navigator.mimeTypes.length; i++)

            document.write(navigator.mimeTypes[i].type + " , ");

document.write(" <br> <br> <b> plugins : </b>" + navigator.plugins.length);

document.write(" <br> <br> <b> plugins : </b> <br>" );

for(i=0; i<navigator.plugins.length; i++)

            document.write(navigator.plugins[i].name + " , ");

        </script>

    </head>

    <body>

    </body>

</html>

15. What is Data Validation? Explain with example.

Data validation is the process of ensuring that a program operates on clean, correct and useful data. It uses routines, often called "validation rules" or "check routines", that check for correctness, meaningfulness, and security of data that are input to the system.

Data validation guarantees to the application that every data value is correct and accurate. We can design data validation into our application with several differing approaches: user interface code, application code, or database constraints.

There are several types of data validation.

·         Data type validation.

·         Range checking.

One of the simplest forms of data validation is verifying the data type. Data type validation answers such simple questions as "Is the string alphabetic?" and "Is the number numeric?" with application's user interface.

Range checking ensures that the provided value is within allowable minimums and maximums. For example, a character data type service code may only allow the alphabetic letters A through Z. All other characters would not be valid.

Program

<html>

   <head>

            <title> Program on Data Validation </title>

      <script language="javascript">

            function check()

            {

               var r = new RegExp("^\\d{5}$");

               var e = new RegExp("^[a-z][\\w]+@+[\\w]+\\.+\\w");

               var pn = pno.value;

               var em = emid.value;

               document.write( "<br> Phone valid : " + r.test(pn) );

               document.write( "<br> emaild valid : " + e.test(em) );

            }

      </script>

   </head>

   <body>

            Enter phone number : <input type="text" name="pno"> <br>

            Enter email-id : <input type="text" name="emid">

            <input type="button" value="validate" onClick="check()" >

   </body>

</html>

16. Write the Message & Confirmation dialogs in JavaScript.

Write the Message & Confirmation dialogs in JavaScript.

1. Alert :The alert built in function is useful for displaying a message on the screen that you don't want your visitors to miss. They will have to select the OK button to proceed. Here is an example of an alert function call:  alert('Alert Message');

              

2. Confirm: The confirm function differs from the alert function only in that it has two buttons to choose between instead of only one. The confirm function returns true or false depending on which of the two buttons is selected. If OK is selected then the confirm function returns true, if Cancel is selected it returns false.

Here's an example of the confirm function:

if (confirm('Select a button'))

alert('You selected OK');

else

alert('You selected Cancel');

               

3. Prompt Box : A prompt box is often used if you want the user to input a value before entering a page. When a prompt box pops up, the user will have to click either "OK" or "Cancel" to proceed after entering an input value.  If the user clicks "OK" the box returns the input value. If the user clicks "Cancel" the box returns null.

Syntax:prompt("sometext","defaultvalue");

     

<html>

<head><title> Alert, Confirm and Prompt dialog boxes </title></head>

<script language="javascript">

alert("Welcome to my webpage...!")

prompt("Enter Your Name:");

confirm("Are You Sure");

document.writeln("Thank You");

</script> 

<body >  </body>

 </html>

17. Explain the Rollover Buttons in JavaScript.

            The most common usage of dynamic HTML is the image rollover. The technique is used to give visual feedback about the location of the mouse cursor by changing the images on the page as the mouse moves over them. This is a highly effective technique, especially where images are used as the hyperlinks in a menu.

 

            The JavaScript rollover is far simpler because it uses two image files which it swaps between as the mouse is moved. One image is created for the inactive state when the mouse is not over it. A second image is created for the active state when the mouse cursor is placed over it. Usually the images are identical apart from some highlighting for the active image.

Program 14:

<html>

    <head>

        <script language="javascript">

            function show1()

            {

            nav.src = "./Sunset.jpg";

            }

            function show2()

            {

            nav.src = "./Winter.jpg";

            }

        </script>

    </head>

    <body>

            Click Here to Go <a href="home.html" onMouseOut="show1()" 

                                                                           onMouseOver="show2()">

            <img src="Winter.jpg" name="nav" width=100 height=100>

            </a>

    </body>

</html>

 

18. Explain Multiple Pages in a single download.

            DHTML opens up some interesting possibilities. One that is fairly obvious but rarely used is having several pages in a single download. The technique behind this is instead of using a separate file for each page, each page of content is placed in a separate layer and switching between them. This technique will not work if the layers have too much content or too many images, simply because the overhead of downloading the page will be too great.

 

However, where most of the data is text-based and where users are going to want to see all of that information from a single page, this is a good trick. It will also work well as a way of splitting a single large document into several screens of data so that users don’t have to scroll up and down.

Program

<html>

    <head>

        <script language="javascript">

            var p="two";

                function show(c)

                {

                document.all(p).style.visibility = "hidden";

                p = c;

                document.all(c).style.visibility = "visible";

                }

       </script>

    </head>

    <body>

        <div id="menu">

            <a href="#" onClick="show('one')"> One </a>

            <a href="#" onClick="show('two')"> Two </a>

        </div>

  <div id="one"  style="{position: absolute; top: 100; left: 50; visibility: hidden;}" >                     <h1> This is layer - 1

        </div>

<div id="two"  style="{position: absolute; top: 100; left: 50; visibility: hidden;}" >

            <h1> This is layer - 2

        </div>

    </body>

</html>

19. Explain the Moving Images with JavaScript.

Because the DOM provides access to styles and style sheets, you can set and change the position of any element as simply as you can set and change its color. This makes it especially easy to change the position of elements based on how the user is viewing the document, and even to animate the elements. For animation, all you need is to modify slightly the position of an element on some interval. The following example presents an image that glides across the page and comes to rest at the left margin.

 

In the following example

·         The image is absolutely positioned.

·         The Start() function unhides the image, sets its position of the image to the far-right edge of the page, and begins calling show() with an interval of 100 milliseconds.

·         The show() function moves the image to the left by 10 pixels, and when the image is finally at the left edge, it cancels the interval.

 

Program

 

<html>

<head>

<title>Dynamic Positioning</title>

<script language="JavaScript">

function Start()

{

                        Banner.style.pixelLeft = document.body.offsetWidth;

                        self.setInterval("show()", 100);

}

function show()

{

                        if(Banner.style.pixelLeft>=0)

                        {

                         Banner.style.pixelLeft=Banner.style.pixelLeft-10;

                         Banner.style.pixelTop=Math.random()*100;

                        }

}

</script>

</head>

<body onload="Start()">

<h3>Welcome to Dynamic HTML!</h3>

<p>With dynamic positioning, you can move images anywhere in the

            document even while the user views the document.</p>

<img id="Banner" Style="{visibility: visible; position:absolute;}"

width=100 height=100 SRC="001.jpg" />

</body>

</html>

 

 

 

Post a Comment

0 Comments