Vous êtes sur la page 1sur 46

1. Explain syntactic characteristics of java script.

Answer:
The syntax of JavaScript is the set of rules that define a correctly structured JavaScript program.
The examples below make use of the alert function for standard text output.
The JavaScript standard library lacks an official standard text output function.
1. JavaScript Lives in a Web Page
2. JavaScript is not server side language. It is client side language because it is interpreted
and run on the browser.
3. It is weakly typed because it does not need to specify datatypes to declare variable (int,
float, double etc) like c/c++.
4. It is not programming language. It Interpreted language because browsers are interpret it.
5. JavaScript is case sensitive.
6. Semicolon(;) is optional
7. String can be enclosed by using single quote () or double quote()
8. // is used to specify single line comment and /* ... */ is used to specify multiline
comment.
Case sensitive
Object oriented
Produces an HTML document
Dynamically typed
Standard operator precedence
Overloaded operators
Reserved words
" and ' can be used in pairs
Scope rules for variables
Strings are very common data types
Rich set of methods available
Arrays have dynamic length
Array elements have dynamic type
Arrays are passed by reference
Array elements are passed by value

2. Explain string manipulation functions with example.


Answer
While JavaScript has many applications, working with string values is one of the most popular.
Strings are objects within the JavaScript language. They are not stored as character arrays, so
built-in functions must be used to manipulate their values. The functions provide various ways to
access the contents of a string variable. Let?s take a closer look at these functions.
The String object lets you work with a series of characters; it wraps Javascript's string primitive
data type with a number of helper methods.
As JavaScript automatically converts between string primitives and String objects, you can call
any of the helper methods of the String object on a string primitive.
Syntax
Use the following syntax to create a String object
Var val = new String(string);
The String parameter is a series of characters that has been properly encoded.
String Properties
Here is a list of the properties of String object and their description.
Property
constructor
length
prototype

Description
Returns a reference to the String function that created the object.
Returns the length of the string.
The prototype property allows you to add properties and methods to an
object.

In the following sections, we will have a few examples to demonstrate the usage of String
properties.
String Methods
Here is a list of the methods available in String object along with their description.
Method
charAt()

Description
Returns the character at the specified index.

concat()

Returns a number indicating the Unicode value of the character at


the given index.
Combines the text of two strings and returns a new string.

indexOf()

Returns the index within the calling String object of the first

charCodeAt()

occurrence of the specified value, or -1 if not found.


Returns the index within the calling String object of the last
occurrence of the specified value, or -1 if not found.
Returns a number indicating whether a reference string comes
before or after or is the same as the given string in sort order.
Used to match a regular expression against a string.

lastIndexOf()
localeCompare()
match()

Used to find a match between a regular expression and a string,


and to replace the matched substring with a new substring.
Executes the search for a match between a regular expression and
a specified string.
Extracts a section of a string and returns a new string.

replace()
search()
slice()
split()
substr()
substring()
toLocaleLowerCase(
)

Splits a String object into an array of strings by separating the


string into substrings.
Returns the characters in a string beginning at the specified
location through the specified number of characters.
Returns the characters in a string between two indexes into the
string.
The characters within a string are converted to lower case while
respecting the current locale.

toLowerCase()

The characters within a string are converted to upper case while


respecting the current locale.
Returns the calling string value converted to lower case.

toString()

Returns a string representing the specified object.

toUpperCase()

Returns the calling string value converted to uppercase.

valueOf()

Returns the primitive value of the specified object.

toLocaleUpperCase()

String HTML Wrappers


Here is a list of the methods that return a copy of the string wrapped inside an appropriate
HTML tag.

Method
anchor()

Description
Creates an HTML anchor that is used as a hypertext target.

big()

Creates a string to be displayed in a big font as if it were in a <big> tag.

blink()

Creates a string to blink as if it were in a <blink> tag.

bold()

Creates a string to be displayed as bold as if it were in a <b> tag.

fixed()

Causes a string to be displayed in fixed-pitch font as if it were in a <tt>


tag
Causes a string to be displayed in the specified color as if it were in a

fontcolor()

italics()

<font color="color"> tag.


Causes a string to be displayed in the specified font size as if it were in a
<font size="size"> tag.
Causes a string to be italic, as if it were in an <i> tag.

link()

Creates an HTML hypertext link that requests another URL.

small()

Causes a string to be displayed in a small font, as if it were in a <small>


tag.
Causes a string to be displayed as struck-out text, as if it were in a
<strike> tag.
Causes a string to be displayed as a subscript, as if it were in a <sub> tag

fontsize()

strike()
sub()
sup()

Causes a string to be displayed as a superscript, as if it were in a <sup>


tag

In the following sections, we will have a few examples to demonstrate the usage of String
methods.
3. Explain mathematical functions with example.

Answer:
The math object provides you properties and methods for mathematical constants and
functions. Unlike other global objects, Math is not a constructor. All the properties and methods
of Math are static and can be called by using Math as an object without creating it.
Thus, you refer to the constant pi as Math.PI and you call the sine function asMath.sin(x),
where x is the method's argument.
Syntax
The syntax to call the properties and methods of Math are as follows
var pi_val = Math.PI;
var sine_val = Math.sin(30);
Math Properties
Here is a list of all the properties of Math and their description.
Property
E\
LN2
LN10
LOG2E
LOG10E
PI

Description
Euler's constant and the base of natural logarithms, approximately 2.718.
Natural logarithm of 2, approximately 0.693.
Natural logarithm of 10, approximately 2.302.
Base 2 logarithm of E, approximately 1.442.
Base 10 logarithm of E, approximately 0.434.
Ratio of the circumference of a circle to its diameter, approximately
3.14159.

SQRT1_2
SQRT2

Square root of 1/2; equivalently, 1 over the square root of 2,


approximately 0.707.
Square root of 2, approximately 1.414.

In the following sections, we will have a few examples to demonstrate the usage of Math
properties.
Math Methods
Here is a list of the methods associated with Math object and their description
Method
abs()
acos()
asin()
atan()
atan2()
ceil()
cos()
exp()
floor()
log()
max()
min()
pow()
random()
round()
sin()
sqrt()
tan()
toSource()

Description
Returns the absolute value of a number.
Returns the arccosine (in radians) of a number.
Returns the arcsine (in radians) of a number.
Returns the arctangent (in radians) of a number.
Returns the arctangent of the quotient of its arguments.
Returns the smallest integer greater than or equal to a number.
Returns the cosine of a number.
Returns EN, where N is the argument, and E is Euler's constant, the base
of the natural logarithm.
Returns the largest integer less than or equal to a number.
Returns the natural logarithm (base E) of a number.
Returns the largest of zero or more numbers.
Returns the smallest of zero or more numbers.
Returns base to the exponent power, that is, base exponent.
Returns a pseudo-random number between 0 and 1.
Returns the value of a number rounded to the nearest integer.
Returns the sine of a number.
Returns the square root of a number.
Returns the tangent of a number.
Returns the string "Math".

In the following sections, we will have a few examples to demonstrate the usage of the methods
associated with Math.

4. What are popup boxes? Explain the different types of popup boxes with
example.
Answer:

JavaScript supports three important types of dialog boxes. These dialog boxes can be used to
raise and alert, or to get confirmation on any input or to have a kind of input from the users.
Here we will discuss each dialog box one by one.
Alert Dialog Box
An alert dialog box is mostly used to give a warning message to the users. For example, if one
input field requires to enter some text but the user does not provide any input, then as a part of
validation, you can use an alert box to give a warning message.
Nonetheless, an alert box can still be used for friendlier messages. Alert box gives only one
button "OK" to select and proceed.
Example
<html>
<head>
<script type="text/javascript">
<!-function Warn() {
alert ("This is a warning message!");
document.write ("This is a warning message!");
}
//-->
</script>
</head>
<body>
<p>Click the following button to see the result: </p>
<form>
<input type="button" value="Click Me" onclick="Warn();" />
</form>
</body>
</html>

Confirmation Dialog Box


A confirmation dialog box is mostly used to take user's consent on any option. It displays a
dialog box with two buttons: Cancel.
If the user clicks on the OK button, the window method confirm() will return true. If the user
clicks on the Cancel button, then confirm() returns false. You can use a confirmation dialog box
as follows.

Example
<html>
<head>
<script type="text/javascript">
<!-function getConfirmation(){
var retVal = confirm("Do you want to continue ?");
if( retVal == true ){
document.write ("User wants to continue!");
return true;
}
else{
document.write ("User does not want to continue!");
return false;
}
}
//-->
</script>
</head>
<body>
<p>Click the following button to see the result: </p>
<form>
<input type="button" value="Click Me" onclick="getConfirmation();" />
</form>
</body>
</html>
Prompt Dialog Box
The prompt dialog box is very useful when you want to pop-up a text box to get user input.
Thus, it enables you to interact with the user. The user needs to fill in the field and then click
OK.
This dialog box is displayed using a method called prompt() which takes two parameters: (i) a
label which you want to display in the text box and (ii) a default string to display in the text box.
This dialog box has two buttons: OK and Cancel. If the user clicks the OK button, the window
method prompt() will return the entered value from the text box. If the user clicks the Cancel
button, the window method prompt()returns null.
Example
The following example shows how to use a prompt dialog box
<html>
<head>

<script type="text/javascript">
<!-function getValue(){
var retVal = prompt("Enter your name : ", "your name here");
document.write("You have entered : " + retVal);
}
//-->
</script>
</head>
<body>
<p>Click the following button to see the result: </p>
<form>
<input type="button" value="Click Me" onclick="getValue();" />
</form>
</body>
</html>

5. Explain creation of an array objects with example.


Answer:
A numerically indexed map of values. Traditionally an array reserves a continuous allocation of
memory of predefined length. In JavaScript this is not the case. A JavaScript array is simply a
glorified object with a unique constructor and literal syntax and an additional set of properties
and methods inherited from Array. Prototype. If this means we make a small sacrifice in
performance, it is more than compensated for by its ease of use and the power of its utilities.
Unlike its counterparts in certain other languages, JavaScript arrays are a joy to use this is
something they definitely got right.
Creating a JavaScript Array
Lets start with the best way. In JavaScript, whenever there is a literal syntax for object creation it
generally makes sense to use it.
//create a new, empty array
var a = [];
//add members to an existing array
a[0] = "Bob";
a[1] = "Mary";
a[2] = "Joe";
//or simply use push
a.push("Jane");
a.push("Carlos");
//create a new array and predefine some members
var b = ["Bob", "Mary", "Joe", "Jane", "Carlos"];

Alternatively you could use the new Constructor syntax. Apart from the obvious drawback of 5-9
additional assaults on your dainty finger pads (the new part is effectively optional) there is a
more serious issue around ambiguity of intention:
//create a new array with 8 undefined members
var a = new Array(8);
//create a new array containing two predefined elements
var b = new Array(8,9);
a.length; //8
b.length; //2
a[0]; //undefined
b[0]; //8
These two declarations look strikingly similar yet produce entirely different results. Moreover,
lets say someone edits the second statement because they now only want to predefine one
element, the number 8, in array b. Its quite likely they might modify it to the following (and who
could blame them?):
//create a new array containing one predefined element
var b = new Array(8); //Wrong!
Of course this doesnt do what they wanted. The only way to predefine an array with one
primitive number is to use the literal syntax. (Thanks Peter and Dmitry for clarification)
An array can contain any object or primitive type. Multiple data types can co-exist in the same
array.
Accessing an Array element
Array elements are simply object properties and are accessed in the same way as other object
properties. Since property identifiers are always strings, the array index is also a string, not a
number. However when you use subscript notation (square brackets) to access the property, a
number literal can also be used since it will be coerced to a string by the interpreter. Dot notation
accessors will not work for array member access because literal property identifiers cant start
with a number (again, all these behaviours derive from generic object property rules, they are not
array-specific)
var a = ["banana", Math.min, 4, "apple"];
a['1']; //min()
a[2]; //4
Typically it makes sense to use the standard for loop:
var a = ["banana", Math.min, 4, "apple"];
for (var i=0; i < a.length; i++) {
console.log(a[i]);
}
If your array is a long one you may be worried about the additional cost of requesting
array.length on every iteration. To workaround this you can define the array length up front:
var a = makeBigArray();
var aLength = a.length;
for (var i=0; i < aLength; i++) {

console.log(a[i]);
}
Using a forin statement for array iteration is not advised because you may also pick up
enumerable properties from the prototype (see below)
The most important array property is length (strings and functions have length too but the array
definition of length is unique)
ECMA specifies:
The length property of this Array object is always numerically greater than the name of every
property whose name is an array index. In other words its (the numeric value of the last index) +
1.Arrays are not upper-bound. You can add an element at an index greater than (length 1) and
the length property will be modified based on the above definition. Arrays have a maximum
length but its too big for you to worry about.
var a = [3,4,1];
a.length; //3
a[20] = 2;
a.length; //21
//element indexes 3-19 automatically created with value initialized to undefined
a[18]; //undefined
Arrays are lower-bound to zero. If you try to add a value at a negative index you will just be
writing a regular object property (see also associative arrays below)
var a = [];
a[-1] = "giraffe";
a[-1]; //"giraffe"; //because still using a regular object property accessor
a.length; //0
a.toString(); //""
You can manipulate the contents of an existing array by updating its length value. If you reduce
the length property of an existing array, members with indexes greater than or equal to the new
length get discarded (this turns out to be the only way to remove indexes from an array you can
delete an element but this will only delete the value and leave the index in place i.e. your array
becomes sparse = it gets holes in it)
var a = [0,1,2,3,4,5,6];
a.length; //7
a.length = 5;
a.toString(); //"0,1,2,3,4"
a[6]; //undefined
Conversely if you increase the length of an existing array by n your array appears to get n new
members, each with its value initialized to undefined however as Dmitry Soshnikov points out,
this is the standard response to accessing a non existent property. In reality nothing has changed
except the array length.

var a = [0,1,2,3,4,5,6];
a.length; //7
a[9]; //undefined
a[59]; //undefined
a.length = 10;
a.toString(); //"0,1,2,3,4,5,6,,,"
a[9]; //undefined
a[59]; //undefined
There are two additional pseudo-properties of arrays: index and input. These properties are only
present in arrays created by regular expression matches. Array provides a plethora of very useful
utilities, there are too many to go into great detail and you are probably familiar with most preECMA 5 functions. The following array methods are available on the latest versions of all major
browsers

concat shallow copy the array and append the arguments


join create a string from the array. Add the argument as glue between each array member
shift remove and return the first element
pop remove and return the last element
unshift append the arguments to the front of the array
push append the arguments to the end of the array
reverse reverses the array without copying it
slice shallow copy the portion of the array delimited by the index arguments
splice removes specified elements from the array, replaces them with optional additional
arguments
sort sorts the array without copying it, optionally using a comparator argument
toString invokes join without passing an argument

ECMA 5 specifies an additional set of high-order functions all of which have already been
implemented by all the major browsers except IE<=8 (but IE9 preview implements them). Many
of these new methods will already be familiar to those of you who make use of the major
JavaScript frameworks:

indexOf returns the first element equal to the specified value, or -1 if none found
lastIndexOf returns the last element equal to the specified value, or -1 if none found
every returns true if the supplied function returns true when applied to every element
some returns true if the supplied function returns true when applied to at least one
element
forEach applies the supplied function to every element in the array
map creates a new array containing the results of applying the supplied function to every
element in the array
filter creates a new array containing all the elements for which the supplied function
returns true

reduce apply a function simultaneously against two values of the array (from left-to-right)
so as to reduce it to a single value (note: reduce had a different meaning in older versions
of Prototype.js)
reduceRight apply a function simultaneously against two values of the array (from rightto-left) so as to reduce it to a single value

The eternal question. The problem is that in JavaScript when you use typeof against an array it
returns object. I nearly wrote an entire blog post on just this topic. Fortunately kangax already
did just that. The upshot is this latest state-of-the-art version of isArray which is simpler and
more robust than any of its slew of predecessors. It also happens to be the implementation
currently used by both jQuery and Prototype.js
function isArray(o) {
return Object.prototype.toString.call(o) === "[object Array]";
}

6. What is function? Explain the function definition and calling a function


with example.
Answer:
A function is a group of reusable code which can be called anywhere in your program. This
eliminates the need of writing the same code again and again. It helps programmers in writing
modular codes. Functions allow a programmer to divide a big program into a number of small
and manageable functions.
Like any other advanced programming language, JavaScript also supports all the features
necessary to write modular code using functions. You must have seen functions
like alert() and write() in the earlier chapters. We were using these functions again and again,
but they had been written in core JavaScript only once.
JavaScript allows us to write our own functions as well. This section explains how to write your
own functions in JavaScript.
Function Definition
Before we use a function, we need to define it. The most common way to define a function in
JavaScript is by using the function keyword, followed by a unique function name, a list of
parameters (that might be empty), and a statement block surrounded by curly braces.

Syntax
The basic syntax is shown here.
<script type="text/javascript">
<!-function functionname(parameter-list)
{
statements
}
//-->
</script>
Example
Try the following example. It defines a function called sayHello that takes no parameters
<script type="text/javascript">
<!-function sayHello()
{
alert("Hello there");
}
//-->
</script>
Calling a Function
To invoke a function somewhere later in the script, you would simply need to write the name of
that function as shown in the following code.
<html>
<head>
<script type="text/javascript">
function sayHello()
{
document.write ("Hello there!");
}
</script>
</head>
<body>
<p>Click the following button to call the function</p>
<form>

<input type="button" onclick="sayHello()" value="Say Hello">


</form>
<p>Use different text in write method and then try...</p>
</body>
</html>

7. Explain function parameter and return statements.


Answer
Function Parameters
Till now, we have seen functions without parameters. But there is a facility to pass different
parameters while calling a function. These passed parameters can be captured inside the
function and any manipulation can be done over those parameters. A function can take multiple
parameters separated by comma.
Example
Try the following example. We have modified our sayHello function here. Now it takes two
parameters.
<html>
<head>
<script type="text/javascript">
function sayHello(name, age)
{
document.write (name + " is " + age + " years old.");
}
</script>
</head>
<body>
<p>Click the following button to call the function</p>
<form>
<input type="button" onclick="sayHello('Zara', 7)" value="Say Hello">

</form>
<p>Use different parameters inside the function and then try...</p>
</body>
/html>
The return Statement
JavaScript function can have an optional return statement. This is required if you want to
return a value from a function. This statement should be the last statement in a function.
or example, you can pass two numbers in a function and then you can expect the function to
return their multiplication in your calling program.
Example
Try the following example. It defines a function that takes two parameters and concatenates
them before returning the resultant in the calling program.
<html>
<head>
<script type="text/javascript">
function concatenate(first, last)
{
var full;
full = first + last;
return full;
}
function secondFunction()
{
var result;
result = concatenate('Zara', 'Ali');
document.write (result );
}
</script>
</head>
<body>

<p>Click the following button to call the function</p>


<form>
<input type="button" onclick="secondFunction()" value="Call Function">
</form>
<p>Use different parameters inside the function and then try...</p>
</body>
</html>

8. List and describe different type of events with example.


Answer:
Event
JavaScript's interaction with HTML is handled through events that occur when the user or the
browser manipulates a page.
hen the page loads, it is called an event. When the user clicks a button, that click too is an event.
Other examples include events like pressing any key, closing a window, resizing a window, etc.
evelopers can use these events to execute JavaScript coded responses, which cause buttons to
close windows, messages to be displayed to users, data to be validated, and virtually any other
type of response imaginable.
vents are a part of the Document Object Model (DOM) Level 3 and every HTML element
contains a set of events which can trigger JavaScript Code.
lease go through this small tutorial for a better understanding HTML Event Reference. Here we
will see a few examples to understand a relation between Event and JavaScript
onclick Event Type
This is the most frequently used event type which occurs when a user clicks the left button of
his mouse. You can put your validation, warning etc., against this event type.
Example
Try the following example.

<html>
<head>
<script type="text/javascript">
<!-function sayHello() {
alert("Hello World")
}
//-->
</script>
</head>
<body>
<p>Click the following button and see result</p>
<form>
<input type="button" onclick="sayHello()" value="Say Hello" />
</form>
</body>
</html>
onsubmit Event type
onsubmit is an event that occurs when you try to submit a form. You can put your form
validation against this event type.
Example
The following example shows how to use onsubmit. Here we are calling avalidate() function
before submitting a form data to the webserver. Ifvalidate() function returns true, the form will
be submitted, otherwise it will not submit the data.
Try the following example.
<html>
<head>
<script type="text/javascript">
<!-function validation() {
all validation goes here
.........

return either true or false


}
//-->
</script>
</head>
<body>
<form method="POST" action="t.cgi" onsubmit="return validate()">
.......
<input type="submit" value="Submit" />
</form>
</body>
</html>
onmouseover and onmouseout
These two event types will help you create nice effects with images or even with text as well.
The onmouseover event triggers when you bring your mouse over any element and
the onmouseout triggers when you move your mouse out from that element. Try the following
Example.
<html>
<head>
<script type="text/javascript">
<!-function over() {
document.write ("Mouse Over");
}
function out() {
document.write ("Mouse Out");
}
//-->
</script>
</head>
<body>
<p>Bring your mouse inside the division to see the result:</p>
<div onmouseover="over()" onmouseout="out()">
<h2> This is inside the division </h2>

</div>
</body>
</html>
HTML 5 Standard Events
The standard HTML 5 events are listed here for your reference. Here script indicates a
Javascript function to be executed against that event.
Attribute
offline
onabort
onafterprint
onbeforeonload
onbeforeprint
onblur
oncanplay

Value
script
script
script
script
script
script
script

oncanplaythrough

script

onchange
onclick
oncontextmenu
ondblclick
ondrag
ondragend
ondragenter

script
script
script
script
script
script
script

ondragleave

script

ondragover
ondragstart
ondrop
ondurationchange
onemptied

script
script
script
script
script

onended
onerror
onfocus
onformchange
onforminput
onhaschange
oninput
oninvalid

script
script
script
script
script
script
script
script

Description
riggers when the document goes offline
riggers on an abort event
riggers after the document is printed
riggers before the document loads
riggers before the document is printed
riggers when the window loses focus
riggers when media can start play, but might has to stop for
buffering
riggers when media can be played to the end, without
stopping for buffering
riggers when an element changes
riggers on a mouse click
riggers when a context menu is triggered
riggers on a mouse double-click
riggers when an element is dragged
riggers at the end of a drag operation
riggers when an element has been dragged to a valid drop
target
riggers when an element is being dragged over a valid drop
target
riggers at the start of a drag operation
riggers at the start of a drag operation
riggers when dragged element is being dropped
riggers when the length of the media is changed
riggers when a media resource element suddenly becomes
empty.
riggers when media has reach the end
riggers when an error occur
riggers when the window gets focus
riggers when a form changes
riggers when a form gets user input
riggers when the document has change
riggers when an element gets user input
riggers when an element is invalid

onkeydown
onkeypress
onkeyup
onload
onloadeddata
onloadedmetadata

script
script
script
script
script
script

onloadstart
onmessage
onmousedown
onmousemove
onmouseout
onmouseover
onmouseup
onmousewheel
onoffline
ononline
onpagehide
onpageshow
onpause
onplay
onplaying
onpopstate
onprogress
onratechange
onreadystatechange
onredo
onresize
onscroll
onseeked

script
script
script
script
script
script
script
script
script
script
script
script
script
script
script
script
script
script
script
script
script
script
script
script

onseeking

script

onselect
onstalled
onstorage
onsubmit
onsuspend

script
script
script
script
script

ontimeupdate
onundo
onunload
onvolumechange

script
script
script
script

riggers when a key is pressed


riggers when a key is pressed and released
riggers when a key is released
riggers when the document loads
riggers when media data is loaded
riggers when the duration and other media data of a media
element is loaded
riggers when the browser starts to load the media data
riggers when the message is triggered
riggers when a mouse button is pressed
riggers when the mouse pointer moves
riggers when the mouse pointer moves out of an element
riggers when the mouse pointer moves over an element
riggers when a mouse button is released
riggers when the mouse wheel is being rotated
riggers when the document goes offline
riggers when the document comes online
riggers when the window is hidden
riggers when the window becomes visible
riggers when media data is paused
riggers when media data is going to start playing
riggers when media data has start playing
riggers when the window's history changes
riggers when the browser is fetching the media data
riggers when the media data's playing rate has changed
riggers when the ready-state changes
riggers when the document performs a redo
riggers when the window is resized
riggers when an element's scrollbar is being scrolled
riggers when a media element's seeking attribute is no
longer true, and the seeking has ended
riggers when a media element's seeking attribute is true,
and the seeking has begun
riggers when an element is selected
riggers when there is an error in fetching media data
riggers when a document loads
riggers when a form is submitted
riggers when the browser has been fetching media data, but
stoppped before the entire media file was fetched
Triggers when media changes its playing position
Triggers when a document performs an undo
Triggers when the user leaves the document
Triggers when media changes the volume, also when

onwaiting

script

volume is set to "mute"


Triggers when media has stopped playing, but is expected
to resume

9. What are cookies? Explain in detail.


Answer:
Cookies
Web Browsers and Servers use HTTP protocol to communicate and HTTP is a stateless
protocol. But for a commercial website, it is required to maintain session information among
different pages. For example, one user registration ends after completing many pages. But how
to maintain users' session information across all the web pages.
In many situations, using cookies is the most efficient method of remembering and tracking
preferences, purchases, commissions, and other information required for better visitor
experience or site statistics.
How It Works
Your server sends some data to the visitor's browser in the form of a cookie. The browser may
accept the cookie. If it does, it is stored as a plain text record on the visitor's hard drive. Now,
when the visitor arrives at another page on your site, the browser sends the same cookie to the
server for retrieval. Once retrieved, your server knows/remembers what was stored earlier.
Cookies are a plain text data record of 5 variable-length fields

Expires The date the cookie will expire. If this is blank, the cookie will expire when the visitor
quits the browser.

Domain The domain name of your site.

Path The path to the directory or web page that set the cookie. This may be blank if you want to
retrieve the cookie from any directory or page.

Secure If this field contains the word "secure", then the cookie may only be retrieved with a secure
server. If this field is blank, no such restriction exists.

Name=Value Cookies are set and retrieved in the form of key-value pairs

Cookies were originally designed for CGI programming. The data contained in a cookie is
automatically transmitted between the web browser and the web server, so CGI scripts on the
server can read and write cookie values that are stored on the client.
JavaScript can also manipulate cookies using the cookie property of theDocument object.
JavaScript can read, create, modify, and delete the cookies that apply to the current web page.
Storing Cookies
The simplest way to create a cookie is to assign a string value to the document.cookie object,
which looks like this.
document.cookie = "key1=value1;key2=value2;expires=date";
Here the expires attribute is optional. If you provide this attribute with a valid date or time, then
the cookie will expire on a given date or time and thereafter, the cookies' value will not be
accessible.
Note Cookie values may not include semicolons, commas, or whitespace. For this reason, you
may want to use the JavaScript escape() function to encode the value before storing it in the
cookie. If you do this, you will also have to use the corresponding unescape() function when
you read the cookie value.
Example
Try the following. It sets a customer name in an input cookie.
<html>
<head>
<script type = "text/javascript">
<!-function WriteCookie()
{
if( document.myform.customer.value == "" ){
alert("Enter some value!");
return;
}
cookievalue= escape(document.myform.customer.value) + ";";
document.cookie="name=" + cookievalue;

document.write ("Setting Cookies : " + "name=" + cookievalue );


}
//-->
</script>
</head>
<body>
<form name="myform" action="">
Enter name: <input type="text" name="customer"/>
<input type="button" value="Set Cookie" onclick="WriteCookie();"/>
</form>
</body>
</html>
Now your machine has a cookie called name. You can set multiple cookies using multiple
key=value pairs separated by comma.
Reading Cookies
Reading a cookie is just as simple as writing one, because the value of the document.cookie
object is the cookie. So you can use this string whenever you want to access the cookie. The
document.cookie string will keep a list of name=value pairs separated by semicolons,
where name is the name of a cookie and value is its string value.
You can use strings' split() function to break a string into key and values as follows
Example
Try the following example to get all the cookies.
<html>
<head>
<script type="text/javascript">
<!-function ReadCookie()
{

var allcookies = document.cookie;


document.write ("All Cookies : " + allcookies );
// Get all the cookies pairs in an array
cookiearray = allcookies.split(';');
// Now take key value pair out of this array
for(var i=0; i<cookiearray.length; i++){
name = cookiearray[i].split('=')[0];
value = cookiearray[i].split('=')[1];
document.write ("Key is : " + name + " and Value is : " + value);
}
}
//-->
</script>
</head>
<body>
<form name="myform" action="">
<p> click the following button and see the result:</p>
<input type="button" value="Get Cookie" onclick="ReadCookie()"/>
</form>
</body>
</html>
Note Here length is a method of Array class which returns the length of an array. We will
discuss Arrays in a separate chapter. By that time, please try to digest it.
Note There may be some other cookies already set on your machine. The above code will
display all the cookies set on your machine.
Setting Cookies Expiry Date
You can extend the life of a cookie beyond the current browser session by setting an expiration
date and saving the expiry date within the cookie. This can be done by setting
the expires attribute to a date and time.
Example

Try the following example. It illustrates how to extend the expiry date of a cookie by 1 Month.
<html>
<head>
<script type="text/javascript">
<!-function WriteCookie()
{
var now = new Date();
now.setMonth( now.getMonth() + 1 );
cookievalue = escape(document.myform.customer.value) + ";"
document.cookie="name=" + cookievalue;
document.cookie = "expires=" + now.toUTCString() + ";"
document.write ("Setting Cookies : " + "name=" + cookievalue );
}
//-->
</script>
</head>
<body>
<form name="myform" action="">
Enter name: <input type="text" name="customer"/>
<input type="button" value="Set Cookie" onclick="WriteCookie()"/>
</form>
</body>
</html>
Deleting a Cookie
Sometimes you will want to delete a cookie so that subsequent attempts to read the cookie
return nothing. To do this, you just need to set the expiry date to a time in the past.
Example
Try the following example. It illustrates how to delete a cookie by setting its expiry date to one
month behind the current date.

<html>
<head>
<script type="text/javascript">
<!-function WriteCookie()
{
var now = new Date();
now.setMonth( now.getMonth() - 1 );
cookievalue = escape(document.myform.customer.value) + ";"
document.cookie="name=" + cookievalue;
document.cookie = "expires=" + now.toUTCString() + ";"
document.write("Setting Cookies : " + "name=" + cookievalue );
}
//-->
</script>
</head>
<body>
<form name="myform" action="">
Enter name: <input type="text" name="customer"/>
<input type="button" value="Set Cookie" onclick="WriteCookie()"/>
</form>
</body>
</html>

10.Describe briefly three major differences between java and java script.
Answer
Difference between Java vs JavaScript
Here is my list of key differences between JavaScript and Java as programming languages. I
have worked both on them, mainly used Java for all Server Side development, Android and
JavaScript for writing client side scripts to do validation, interactivity, animation and ajax calls.

1. Execution Environment
First difference between Java and JavaScript is that Java is compiled + interpreted language, Java
code is fist compiled into class files containing byte code and than executed by JVM, on the
other hand JavaScript code is directly executed by browser. One more difference which comes
form this fact is that, Java is run inside JVM and needs JDK or JRE for running, on there other
hand JavaScript runs inside browser and almost every modern browser supports JavaScript.

2. Static vs Dynamic Typed language


Another key difference between JavaScript and Java is that, JavaScript is a dynamic typed
language, while Java is a statically typed language. Which means, variables are declared with
type at compile time, and can only accept values permitted for that type, other hand variables are
declared using vary keyword in JavaScript, and can accept different kinds of value
e.g. String, numeric andboolean etc. When one variable or value is compared to other using ==
operator, JavaScript performs type coercion. Though it also provides === operator to perform
strict equality check, which checks for type as well. See here for more differences between ==
and == operator in JavaScript.
3. Support of Closures
JavaScript supports closures, in form of anonymous function. In simple words, you can pass a
function as an argument to another function. Java doesn't treat method as first class citizen and
only way to simulate closure is by using anonymous class. By the way Java 8 has brought real
closure support in Java in form of lambda expression and this has made things much easier. It's
very easy to write expressive code without much clutter in Java 8.
4. OOP
Java is an Object Oriented Programming language, and though JavaScript also supports class and
object, it's more like an object oriented scripting language. It's much easier to structure code of
large enterprise application in Java then JavaScript. Java provides packages to group related class
together, provides much better deployment control using JAR, WAR and EAR as well.
5. Right Once Run Anywhere
Java uses byte code to achieve platform independence, JavaScript directly runs on browser, but
code written in JavaScript is subject to browser compatibility issue i.e. certain code which work
in Mozilla Firefox, may not work in Internet Explorer 7 or 8. This is because of browse based
implementation of JavaScript. This was really bad until jQuery comes. Its a JavaScript library
which helps to free web developers from this browser compatibility issues. This is why I prefer

to write code using jQuery rather than using plain old JavaScript code, even if its as simple as
calling getElementById() or getElementByName() methods to retrieve DOM elements.
6. Block vs Function based Scoping
Java mainly uses block based scoping i.e. a variable goes out of scope as soon as control comes
out of the block, unless until its not a instance or class variable. On the other hand JavaScript
mainly uses function based scoping, a variable is accessible in the function they are declared. If
you have a global variable and local variable with same name, local will take precedence in
JavaScript.

7. Constructors
Java has concept of constructors, which has some special properties e.g. constructor
chaining and ensuring that super class constructor runs before sub class, on the other hand
JavaScript constructors are just another function. There is no special rules for constructors in
JavaScript e.g. they cannot have return type or their name must be same as class.
8. NullPointerException
JavaScript is much more forgiving than Java, you don't have NullPointerException in
JavaScript, your variable can accept different kinds of data because of JavaScript is dynamically
typed language.
9. Applicability
Last but not the least, JavaScript has it's own space, sitting cozy along with HTML and CSS in
Web development, while Java is everywhere. Though both has good number of open source
libraries to kick start development, but jQuery has certainly brings JavaScript on fore front.

11. What is pattern matching in java script


Answer
Pattern matching is a form of conditional branching which allows you to concisely match on
data structure patterns and bind variables at the same time.JavaScript provides two ways to do
pattern matching:
1. Using RegExp objects
2. Using methods on String objects

RE in both ways are the same as in Perl


Simple patterns
Two categories of characters in patterns:
a. normal characters (match themselves)
b. metacharacters (can have special meanings
in patterns--do not match themselves)
\|()[]{}^$*+?.
- A metacharacter is treated as a normal
character if it is backslashed
- period (.) is a special metacharacter - it
matches any character except newline
create RegExp objects
var varname = / reg_ex_pattern / flags
Simplest example: exact match
To match occurrence of our in a string containing.
1. Matching in RegExp objects
Tests a string for pattern matches. This method returns a Boolean that indicates whether or not
the specified pattern exists within the searched string. This is the most commonly used method
for validation. Use test() method of RegExp object
Format: regexp.test( string_to_be_tested )
test() returns a Boolean
2. Matching in Strings
var tomatch=/our/;
var result = tomatch.test(pour); //boolean result
search() method
Returns the position in the specified string of the RE pattern (position is relative to zero); returns
-1 if it fails
var str = "Gluckenheimer";
var position = str.search(/n/);
/* position is now 6 */

match() method
compares a RE and a string to see whether they match.

replace() method
finds out if a RE matches a string and then replaces a matched string with a new string
search() method
Format: string.search(reg-exp)
Searches the string for the first match to the given regular expression
returns an integer that indicates the position in the string (zero-indexed).
If no match is found, the method will return 1.
Similar to the indexOf() method,
Example: To find the location of the first absolute link within a HTML document
pos = htmlString.search(/^<a href = http:\/\/$/i);if ( pos != -1) { alert( First absolute
link found at + pos +position.);}else { alert ( Absolute links not found)

match() method
Format: string.match( regular_expression )
returns an array of all the matching strings found in the string given. If no matches are found,
then match() returns false.
Example: To check the proper format for a phone number entered by a user, with the form of
(XXX) XXX-XXXX.
function checkPhone( phone ) { phoneRegex = /^\(\d\d\d\) \d\d\d-\d\d\d\d$/; if( !
phone.match( phoneRegex ) ) { alert( Please enter a valid phone number ); return
false; } return true;}
replace() method
Format string.replace(reg_exp)
Properties: replaces matches to a given regular expression with some new string.
Example: To replace every newline character (\n) with a break <br /> tag,
comment = document.forms[0].comments.value;
/* assumes that the HTML form is the first one present in the document, and it has a field
named comments */
comment = comment.replace( /\n/g, <br />);
function formatField( fieldValue ) { return fieldValue = fieldValue. replace(/\n/g, <br />);}
The function accepts any string as a parameter, and returns the new string with all of the newline
characters replaced by <br /> tags.

12 Explain the DOM structure of a document with figure


Answer

The Document Object Model (DOM) is a programming API for HTML and XML documents. It
defines the logical structure of documents and the way a document is accessed and manipulated.
In the DOM specification, the term "document" is used in the broad sense - increasingly, XML is
being used as a way of representing many different kinds of information that may be stored in
diverse systems, and much of this would traditionally be seen as data rather than as documents.
Nevertheless, XML presents this data as documents, and the DOM may be used to manage this
data.
The Document Object Model is a programming API for documents. The object model itself
closely resembles the structure of the documents it models. For instance, consider this table,
taken from an HTML document:
<TABLE>
<ROWS>
<TR>
<TD>Shady Grove</TD>
<TD>Aeolian</TD>
</TR>
<TR>
<TD>Over the River, Charlie</TD>
<TD>Dorian</TD>
</TR>
</ROWS>
</TABLE>
The Document Object Model represents this table like this:

In the Document Object Model, documents have a logical structure which is very much like a
tree; to be more precise, it is like a "forest" or "grove" which can contain more than one tree.
However, the Document Object Model does not specify that documents be implemented as a tree
or a grove , nor does it specify how the relationships among objects be implemented in any way.
In other words, the object model specifies the logical model for the programming interface, and
this logical model may be implemented in any way that a particular implementation finds
convenient. In this specification, we use the term structure model to describe the tree-like
representation of a document; we specifically avoid terms like "tree" or "grove" in order to avoid
implying a particular implementation. One important property of DOM structure models
is structural isomorphism: if any two Document Object Model implementations are used to

create a representation of the same document, they will create the same structure model, with
precisely the same objects and relationships.

13 What is event handling? Explain any three events in java script


Answer: Refer question no 8

14 How do you handle events of text box and password elements?


Answer
Handling Events from Textbox and Password Elements

The Focus Event


Can be used to detect illicit changes to a text box by blurring the element every time the
element acquires focus
Checking Form Input
A good use of JavaScript, because it finds errors in form input before it is sent to the
server for processing so, it saves both:

1. Server time, and


2. Internet time
Things that must be done:
1. Detect the error and produce an alert message
2. Select the element (the select function)
The select function highlights the text in the element to keep the form active after the event
handler is finished, the handler must return false
Example comparing passwords
The form just has two password input boxes to get the passwords and Reset and Submit
buttons the event handler is triggered by the Submit button compare this Submit button with that
in the e-commerce case
Handler actions:

1. If no password has been typed in the first box, focus on that box and return false
2. If the two passwords are not the same, focus and select the first box and return false if
they are the same, return true

15 Write a java script program to validate Employee form


Answer
<html>
<head>
<title>Registration Form</title>
<script type="text/javascript">
<!-function validate_form ( )
{
if ( document.emp.emp_name.value == "" )
{
alert ( "Please fill in the 'Your Employee Name' box." );
return false;
}
if ( document.emp.num.value == "" )
{
alert ( "Enter Employee Number" );
return false;
}
alert("sucessfully Submitted");
return true;
}
if (!(/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/).test(document.emp.email_id.value))
{
alert("You have entered an invalid email address!")
return (false)
}
function isNumberKey(evt)
{
var charCode = (evt.which) ? evt.which : event.keyCode;
if (charCode != 46 && charCode > 31
&& (charCode < 48 || charCode > 57))
{alert("Enter Number");
return false;
}
return true;
}
//-->
</script>

</head>
<body bgcolor="#FFFFFF">
<form name="emp" action="" onsubmit="return validate_form();" method="post">
<table align="center" width=40% width="100%" cellspacing="2" cellpadding="2" border="5">
<tr>
<td colspan="2" align="center"><b>Employee Registration Form.</b></td>
</tr>
<tr>
<td align="left" valign="top" width="41%">Employee Name<span
style="color:red">*</span></td>
<td width="57%"><input type="text" value="" name="emp_name" size="24"></td>
</tr>
<tr>
<td align="left" valign="top" width="41%">Employee Number<span
style="color:red">*</span></td>
<td width="57%">
<input type="text" value="" name="num" onkeypress="return isNumberKey(event)"
size="24"></td>
</tr>
<tr>
<td align="left" valign="top" width="41%">Address</td>
<td width="57%"><textarea rows="4" maxlen="200" name="S2" cols="20"></textarea></td>
</tr
<tr >
<td align="left" valign="top" width="41%">Contact Number</td>
<td width="57%">
<input type="text" value="" onkeypress="return isNumberKey(event)" name="txtFName1"
size="24"></td>
</tr>
<tr >
<td align="left" valign="top" width="41%">Job Location</td>
<td width="57%"><select name="mydropdown">
<option value="Default">Default</option>
<option value="Chennai">Chennai</option>
<option value="Bangalore">Bangalore</option>
<option value="Chennai">Pune</option>
<option value="Bangalore">Mysore</option>
<option value="Chennai">Chandigarh</option>
</select></td>
</tr>
<tr >
<td align="left" valign="top" width="41%">Designation</td>
<td width="57%">
<select name="mydropdown">
<option value="Default">Default</option>
<option value="Systems Engineer">Systems Engineer</option>

<option value="Senior Systems Engineer">Senior Systems Engineer</option>


<option value="Technology Analyst">Technology Analyst</option>
<option value="Technology Lead">Technology Lead</option>
<option value="Project Manager">Project Manager</option>
</select></td>
</tr>
<tr>
<td align="left" valign="top" width="41%">Email<span style="color:red">*</span></td>
<td width="57%">
<input type="text" value="" name="email_id" size="24"></td>
</tr>
<tr>
<td colspan="2">
<p align="center">
<input type="submit" value=" Submit"
name="B4">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&n
bsp;&nbsp;&nbsp;&nbsp;
<input type="reset" value=" Reset All " name="B5"></td>
</tr>
</table>
</form>
</body>
</html>

16 Describe the approach of to addressing XHTML elements by using


getElementById.
Answer
Javascript provides the ability for getting the value of an element on a webpage as well as
dynamically changing the content within an element. Getting the value of an element To get the
value of an element, the getElementById method of the document object is used. For this method
to get the value of an element, that element has to have an id given to it through the id attribute.
Example:
<script type="text/javascript">
function getText()
{
//access the element with the id 'textOne' and get its value //assign this value to the variable
theText var
theText = document.getElementById('textOne').value;
alert("The text in the textbox is " + theText);
}
</script>

<input type="text" id="textOne" />


<input type="button" value="Get text" onclick="getText()" />
Changing the content within an element To change the content within an element, use the
innerHTML property. Using this property, you could replace the text in paragraphs, headings and
other elements based on several things such as a value the user enters in a textbox. For this
property to change the content within an element, that element has to have an 'id' given to it
through the id attribute.
Example:
<script type="text/javascript">
function changeTheText()
{ //change the innerHTML property of the element whose id is 'text' to 'So is HTML!'
document.getElementById('text').innerHTML = 'So is HTML!'; }
</script>
<p id="text">Javascript is cool!</p>
<input type='button' onclick='changeTheText()' value='Change the text' />
You can also change the text of elements based on user input:
Example:
<script type="text/javascript">
function changeInputText(){
/* change the innerHTML property of the element whose id is 'theText' to the value from the
variable usersText which will take the value from the element whose id is 'usersText' */
var usersText = document.getElementById('usersText').value;
document.getElementById('theText').innerHTML = usersText;
}
</script>
<p id="theText">Enter some text into the textbox and click the buttton</p>
<input type="text" id="usersText" />
<br />
<input type="button" onclick="changeInputText()" value="Change the text" />

17 What is the difference between exception handling and event handling?


Answer
SR.N
O
1

Exception Handling
Exceptions are time to learn how to stop

Event Handling
Events occur when some sort of

them from crashing our program

interaction takes place in a web page

Java script handle the exception via the


try.catch.finally statement which is
similar to other language
The first part of try statement the try
clause is mandatory and is used to
eliminate block of code that the
programmer suspect could generate an
exception
Second part catch statement. The catch
clause is block of code that is only
executed if an exception occurs in the
try clause
The last statement finally the clause is a
block of code that is executed after the
try and catch clause regardless of any
errors

This can be handle end user clicking on


something movie the mouse over certain
element keys on keyboard
An event can also something that happens
in the web browser such as the web page
completing the loading of a page

Through the user of java script you can


detect when certain events happen in cause
things to occur in response to those events
Event capturing start with the out most
elements in the DOM event begins by
checking the target of the events for any
attached events handles.

18 What is the difference between constructor in Java and in JavaScript?


Answer:
SR
NO
1

Constructor in java
Java constructors are special functions
that can only be called at object creation.

Constructor in Java Script


JavaScript "constructors" are just standard
functions.

2
Java constructor is invoked at the time of In JavaScript, the constructor property
object creation. It constructs the values i.e. returns the constructor function for an
provides data for the object that is why it object.
is known as constructor.

Constructor must not have return type.


1.

In JavaScript, the constructor property


returns the constructor function for an
object.

The term constructor is usually meant to


mean function constructor.

Most in the community use the term full


term since JS has no classes, and function
constructor is more clear.

19 Describe the two ways of the properties of an object can be referenced.


Answer
Object properties can be any of the three primitive data types, or any of the abstract data types,
such as another object. Object properties are usually variables that are used internally in the
object's methods, but can also be globally visible variables that are used throughout the page.
The syntax for adding a property to an object is
objectName.objectProperty = propertyValue;
Object Methods
Methods are the functions that let the object do something or let something be done to it. There
is a small difference between a function and a method at a function is a standalone unit of
statements and a method is attached to an object and can be referenced by the this keyword.
Methods are useful for everything from displaying the contents of the object to the screen to
performing complex mathematical operations on a group of local properties and parameters.
User-Defined Objects
All user-defined objects and built-in objects are descendants of an object called Object.
The new Operator
The new operator is used to create an instance of an object. To create an object,
the new operator is followed by the constructor method.
In the following example, the constructor methods are Object(), Array(), and Date(). These
constructors are built-in JavaScript functions.
The 'with' Keyword

The with keyword is used as a kind of shorthand for referencing an object's properties or
methods.
The object specified as an argument to with becomes the default object for the duration of the
block that follows. The properties and methods for the object can be used without naming the
object.
Syntax
The syntax for with object is as follows
with (object){
properties used without the object name and dot
}

Example
<html>
<head>
<title>User-defined objects</title>
<script type="text/javascript">
// Define a function which will work as a method
function addPrice(amount){
with(this){
price = amount;
}
}
function book(title, author){
this.title = title;
this.author = author;
this.price = 0;
this.addPrice = addPrice; // Assign that method as property.
}
</script>
</head>
<body>

<script type="text/javascript">
var myBook = new book("Perl", "Mohtashim");
myBook.addPrice(100);
document.write("Book title is : " + myBook.title + "<br>");
document.write("Book author is : " + myBook.author + "<br>");
document.write("Book price is : " + myBook.price + "<br>");
</script>
</body>
</html>

20 Describe the approach to addressing XHTML elements using


a. Forms and elements
b. Name attributes
a.Forms and elements
The getElementById and getElementsByName methods can be used to obtain references to
forms and form elements. The getElementById method returns the single matching element with
the specified ID; getElementsByName returns an array-like list of elements[1] that match the
name specified.
An example demonstrates with two radio buttons that have the name gender:
markup generated using prism.js (prismjs.com)
<input type="radio" name="gender" value="male" /> male
<input type="radio" name="gender" value="female" /> female
The following demonstrates obtaining references to them using getElementsByName:
var gender = document.getElementsByName('gender');
alert( gender.length ); // 2
// view the value of the first element with name gender
alert( gender[0].value ); // male
The getElementsByName method is defined on document, so it could not be used to find
elements with a particular name in a specific form. The getElementsByName method is seldom
used, yet it does have broad browser support.
The getElementsByTagName, querySelectorAll, and other methods discussed in Obtaining
Element References in JavaScript can also be used to reference forms and form elements.

b.Name attributes

There would be no particular need to apply a name attribute to a form. The form name attribute is
not valid in XHTML. Using an ID rather than a name to identify and obtain a reference to a form
is generally preferable.
On the other hand, name attributes on form elements are valid and necessary for successful
submission to server side code. If you are associating a label element with a form element using
a for attribute, the form element needs an ID:
<label for="firstName">First Name: </label>
<input type="text" name="firstName" id="firstName" />
Thus, form elements will typically include a name attribute and may also include an ID attribute
if needed. Keep in mind that IDs need to be unique in the document, while the same name may
be applied to multiple form elements. This is typical with sets of radio inputs and often
checkboxes as well.

21 Explain three phases of event processing in DOM2 event model.


Answer

1
2
3

DOM event flow


The DOM event flow is the process through which the event originates from the DOM Events
implementation and is dispatched into a tree. Each event has an event target, a targeted node in
the case of the DOM Event flow, toward which the event is dispatched by the DOM Events
implementation.
Phases
The event is dispatched following a path from the root of the tree to this target node. It can then
be handled locally at the target node level or from any target's ancestors higher in the tree. The
event dispatching (also called event propagation) occurs in three phases and the following order:
The capture phase: the event is dispatched to the target's ancestors from the root of the tree to the
direct parent of the target node.
The target phase: the event is dispatched to the target node.
The bubbling phase: the event is dispatched to the target's ancestors from the direct parent of the
target node to the root of the tree.

Figure: graphical representation of an event dispatched in a DOM tree using the DOM event
flow
The target's ancestors are determined before the initial dispatch of the event. If the target node is
removed during the dispatching, or a target's ancestor is added or removed, the event propagation
will always be based on the target node and the target's ancestors determined before the dispatch.
Some events may not necessarily accomplish the three phases of the DOM event flow, e.g. the
event could only be defined for one or two phases. As an example, events defined in this
specification will always accomplish the capture and target phases but some will not accomplish
the bubbling phase ("bubbling events" versus "non-bubbling events", see also the Event.bubbles
attribute).

22 Create a simple HTML page which includes simple form write a script to
extract the data from the form when the submit button is clicked. Display
the extracted data in a new document
Answer
<html>
<head>
<title>contact</title>
<script type="text/javascript">
function addtext()
{
var fname = document.myform.first_name.value;
var lname = document.myform.last_name.value;
var email = document.myform.email.value;
document.writeln("thank you! You have just entered the following:");
document.writeln("<pre>");

document.writeln("first name : " + fname);


document.writeln("last name : " + lname);
document.writeln("email address : " + email);
}
</script>
</head>
<body>
<center>
<b>contact us</b> <br></br>
<form name="myform">
<label for="first_name">first name </label>
<input type="text" name="first_name" maxlength="50" size="30">
<br>
<label for="last_name">last name </label>
<input type="text" name="last_name" maxlength="50" size="30">
<br>
<label for="email">email address</label>
<input type="text" name="email" maxlength="80" size="30">
<br>
<input type="submit" value="submit" onclick="addtext()">
</form>
</body>
</html>

23 What relationship is there between the value of the length property of an


array object and the actual number of existing elements in the object.
Answer
Relationship between length and numerical properties
An array's length property and numerical properties are connected. Here is some code explaining
how this relationship works.
var a = [];
a[0] = 'a';
console.log(a[0]); // 'a'
console.log(a.length); // 1
a[1] = 32;
console.log(a[1]); // 32
console.log(a.length); // 2
a[13] = 12345;
console.log(a[13]); // 12345
console.log(a.length); // 14

a.length = 10;
console.log(a[13]); // undefined, when reducing the length elements after length+1 are removed
console.log(a.length); // 10
The result of a match between a regular expression and a string can create an array. This array
has properties and elements that provide information about the match. An array is the return
value of RegExp.exec, String.match, and String.replace. To help explain these properties and
elements, look at the following example and then refer to the table below:
// Match one d followed by one or more b's followed by one d
// Remember matched b's and the following d
// Ignore case
var myRe = /d(b+)(d)/i;
var myArray = myRe.exec("cdbBdbsbz");

24 Define the scope of a variable in a JavaScript script embedded in an


XHTML document when the variable is not declared in a function.
Answer
Example: Variables and Functions prompt(), confirm()
This script prompts the user for his/her name, confirms the name, and prints a greeting message.
There are three kinds of pop-up dialog boxes for interacting with the users:
1 The alert(aString) function puts the aString on a pop-up box with a OK button. User
needs to click the OK button to continue.
2 The prompt(promptingString, defaultInputString?) function puts up an input pop-up box
with the promptingString with an OK and Cancel buttons. It returns the input entered by
the user as a string; or a special value called null if the user hits the Cancel button. The
optional parameter defaultString specifies the initial string to be shown. In this article, I
shall indicate optional function parameters with a trailing '?' for compactness.
3 The confirm(aString) function puts aString on a pop-up box with OK and Cancel buttons.
It returns true if user hits the OK button; or false otherwise.
JSExVar.html
<!DOCTYPE html>
<!-- JSExVar.html -->
<html lang="en">
<head>
<meta charset="utf-8">
<title>JavaScript Example: Variables and functions prompt() and confirm()</title>
<script>
var username = prompt("Enter your name: ", "");
if (confirm("Your name is " + username)) {
document.write("<h1>Hello, " + username + "!</h1>");
} else {
document.write("<h1>Hello, world!</h1>");

}
</script>
</head>
<body>
<p>Welcome to JavaScript!</p>
</body>
</html>
1
2
3
4

How it Works?
Line 8 declares a variable called username, via the keyword var. A variable is a named storage
location that holds a value. Once the variable is declared, you can assign (and re-assign) a value
to that variable, via the assignment operator '=' (Line 9).
Line 9 invokes the prompt(promptingString, defaultString?) function to pop out a dialog box,
and reads in the string entered by the user. The string read is assigned to the variable username.
The function prompt() is similar to the alert(), but it accepts a user's input.
In Line 10, the confirm(aString) function puts up the message and returns either true or false,
depending on whether the user hits the OK or Cancel button.
If the result is true, Line 11 prints "Hello, username!". Otherwise, Line 13 prints "Hello, world!".
TRY: Instead of printing the greeting message using document.write(), do it via an alert().

25 How does java script fare as an object oriented language? Would it be


correct to say that java script is object based rather than object oriented.
Answer
Stages of a JavaScript Developer Despite the current popularity of JavaScript in the browser, its
actually very difficult to find developers who understand it well. This is true in any job market,
whether it be the Bay Area, the deeply digital tech sector of Vancouver, or even the highly
professional New York developer community. This is fundamentally because the
interconnectedness between JavaScript and related technologies (CSS, HTML, and the browser)
creates deep complexities that only an enthusiast can fully master. Its also because a thorough
understanding of server technologies and transport formats like XML, JSON, and SOAP is often
required. Rarely will you see a job posting for a JavaScript expert but instead for a multidiscipline developer experienced in JavaScript as well as many other technologies. As a result,
some developers are choosing to become adept at one or more of the popular JavaScript
frameworks such as jQuery, Dojo, Prototype, or Mootools. These are very practical ways to
approach browser scripting, and I highly recommend learning one, but these frameworks are by
nature minimalistic. They are not particularly forgiving if you lack an understanding of CSS,
Object Orientation, or interacting with the document object model. If youre new to the

language, youre probably overwhelmed with the number of resources available for learning it.
You may have read some other books or even tried your hand at some basic scripting. Its
possible to rapidly accelerate your mastery of both JavaScript and browser scripting in general
by familiarizing yourself with the fundamentals. If you already know another programming
language and can become proficient with the four or so basic concepts in the language, you can
say goodbye to months of gradual discovery and terrible code and jump right into the really fun
stuff. John Resig of jQuery and Mozilla fame was one of the first to describe a common
development path for new coders when learning
Object references are everywhere: Most useful operations involve passing references to very
large objects like the DOM (Document Object Model) or an element on the page or a function.
The DOM itself is a very large hierarchical collection of object and element references that can
be manipulated as easily as setting a property. You can make your own objects and
namespaces: Indeed, one of the first things developers realize is that JavaScript is OO (Object
Oriented) programming. While they may not fully understand all the OO features available to
them, they begin by making some basic APIs that follow very elementary OO principals.
Object prototypes let you create OO classes: Once coders understand that they can create
instances of objects and functions to build pseudo-classes, someone points out the prototype
constructor to them and somewhere in the learners brains a light goes off. They begin building
elaborate class-based APIs for every imaginable purpose but begin hitting roadblocks related to
scope and maintaining object references between pieces of their programs. Closures are God:
As Resig pointed out in his now-famous talk, at this stage coders generally discover how
closures can help solve some of the problems encountered in stage 3 when building complex
interconnected APIs. They may not, however, fully understand the minefield that closures are.
Memory leaks, difficult-to-follow scope chains, and spaghetti code are coexistent with a coders
first attempts at closures.

Vous aimerez peut-être aussi