You are on page 1of 26

WWW.VIDYARTHIPLUS.

COM
Introduction to DOM

 The Document Object Model is a programming API for documents. The object model
itself closely resembles the structure of the documents it models.
 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.
 With the Document Object Model, programmers can create and build documents,
navigate their structure, and add, modify, or delete elements and content. Anything found
in an HTML or XML document can be accessed, changed, deleted, or added using the
Document Object Model, with a few exceptions

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:

DOM representation of the example table

WWW.VIDYARTHIPLUS.COM BATHUSHA
WWW.VIDYARTHIPLUS.COM

The DOM is the present and future of browsers, and no doubt it will become the only supported
technique for both basic and advanced DHTML in the future.

The W3C DOM is supported by 5th generation browsers. These currently include:

 Opera 7+

 Mozilla Gecko (Mozilla, Firefox, Netscape 6+)

 KHTML/WebKit (Konqueror 2+, Safari, OmniWeb 4.5+)

 Internet Explorer 5+

 iCab 3+ (2- is passive only)

 ICEbrowser

 Escape/Evo 5 (partial only [and broken])

 Tkhtml Hv3 (partial only [and broken])

 NetFront 3+ (partial only)

 Netgem 4 browser (NetBox) - not tested

 OpenTV - not tested

 iPanel MicroBrowser with advanced modules - not tested

WHY DOM?

An HTML page is rendered in a browser.The browser assembles all the elements in the
HTMLpage in memory and once done it renders these object in the browser window. Once the
page is rendered it can no longer recognize the individual elements.

WWW.VIDYARTHIPLUS.COM BATHUSHA
WWW.VIDYARTHIPLUS.COM
Javascript enabled browsers are capable of recognizing individual elements using the
concept tof DOM.

The HTML objects which belong to DOM has a descending relationship with each other. The top
most object in DOM is Navigator. The next level is the DOCUMENT. The DOM continues to
encompass the individual elements of FORM.

JAVASCRIPT’s DOM Hierarchy

Navigator

->Window

->Document

->Anchor

->Link

->Form

->textbox

->textarea

->radiobutton

->checkbox

->select

->button

JAVASCRIPT ASSISTED STYLE SHEETS DOM (JSSS DOM)

JSSS use Javascript syntax to control a documents presentation styles. When a JSSS is
embedded in an HTML page, the Javascript DOM adds additional objects into the DOM.

JSSS DOM

Document

->Tags

-> P

->DIV

WWW.VIDYARTHIPLUS.COM BATHUSHA
WWW.VIDYARTHIPLUS.COM
->SPAN

->H1 thru H6

->Classes

->Tag Names

->IDS

Since Javascript understands the Dom and can extend the DOM, Javascript understands objects.

All objects have,

Properties: that determine the functionality of the Object.

Objectname.PropertyName=value

Methods; that allow access to the properties.

ObjectName.MethodName

Events: that allow Java code snippets to be mapped to appropriate event handlers.

Javascript is an object-based programming language and it is not fully object oriented.

BROWSER OBJECT MODEL (BOM)

Browser Objects

When any Javascript enabled browser loads a web page, the browser automatically
creates a number of Javascript Objects that map to the Dom. The java script code embedded
within <script> tag makes use of these objects to interact with the HTML objects in the page.

Navigator
A Javascript
enabled Window The web page
Browswer loaded
Document containing all
theHTML
Screen elements to
Location which javascript
requires access
EVENT History

Event
Common context area in Computer Memory

OBJECTS USE
NAVIGATOR To access information about the Browser

WWW.VIDYARTHIPLUS.COM BATHUSHA
WWW.VIDYARTHIPLUS.COM
WINDOW To access a window/frame in a window
DOCUMENT To access the document currently loaded in
a window.
LOCATION To represent a URL
HISTORY To maintain the history of URL accessed.
Event To access info about the occurrence of
event.
EVENT Provides constants that are used to identify

Events.
SCREEN To access info’ about the size and color
depth of the screen.

I. Window Object

The window object represents an open window in a browser.

If a document contain frames (<frame> or <iframe> tags), the browser creates one window object
for the HTML document, and one additional window object for each frame.

Window Object Properties

Property Description
closed Returns a Boolean value indicating whether a window has been closed or not
defaultStatus Sets or returns the default text in the statusbar of a window
document Returns the Document object for the window
frames Returns an array of all the frames (including iframes) in the current window
history Returns the History object for the window
innerHeight Sets or returns the the inner height of a window's content area
innerWidth Sets or returns the the inner width of a window's content area
length Returns the number of frames (including iframes) in a window
location Returns the Location object for the window
name Sets or returns the name of a window
navigator Returns the Navigator object for the window
opener Returns a reference to the window that created the window
outerHeight Sets or returns the outer height of a window, including toolbars/scrollbars
outerWidth Sets or returns the outer width of a window, including toolbars/scrollbars
pageXOffset Returns the pixels the current document has been scrolled (horizontally) from
the upper left corner of the window
pageYOffset Returns the pixels the current document has been scrolled (vertically) from
the upper left corner of the window
parent Returns the parent window of the current window
screen Returns the Screen object for the window
screenLeft Returns the x coordinate of the window relative to the screen
screenTop Returns the y coordinate of the window relative to the screen

WWW.VIDYARTHIPLUS.COM BATHUSHA
WWW.VIDYARTHIPLUS.COM
screenX Returns the x coordinate of the window relative to the screen
screenY Returns the y coordinate of the window relative to the screen
self Returns the current window
status Sets the text in the statusbar of a window
top Returns the topmost browser window

Window Object Methods

Method Description
alert() Displays an alert box with a message and an OK button
blur() Removes focus from the current window
clearInterval() Clears a timer set with setInterval()
clearTimeout() Clears a timer set with setTimeout()
close() Closes the current window
confirm() Displays a dialog box with a message and an OK and a Cancel button
createPopup() Creates a pop-up window
focus() Sets focus to the current window
moveBy() Moves a window relative to its current position
moveTo() Moves a window to the specified position
open() Opens a new browser window
print() Prints the content of the current window
prompt() Displays a dialog box that prompts the visitor for input
resizeBy() Resizes the window by the specified pixels
resizeTo() Resizes the window to the specified width and height
scroll()
scrollBy() Scrolls the content by the specified number of pixels
scrollTo() Scrolls the content to the specified coordinates
setInterval() Calls a function or evaluates an expression at specified intervals (in
milliseconds)
setTimeout() Calls a function or evaluates an expression after a specified number of
milliseconds

A new browser window opens using the open() method of a window object.

General Syntax of the open() method of window object:

window.open(URL,name,specs,replace)

In the above, all the fields (URL, name, specs, replace) given in arguments are optional.

WWW.VIDYARTHIPLUS.COM BATHUSHA
WWW.VIDYARTHIPLUS.COM
The URL given in the argument of the open() method of window object specifies the URL of the
page to open. If the user does not mention any URL, then an empty window will be created and
opened.

The name field specified in the open() method of window object is a string denoting the name of
the new window. This can be used as the target attribute.

The most commonly used values are:

 _blank This is a default value that denotes that the URL is loaded into a new window.
 _parent This denotes that the URL is loaded into the parent frame.
 _self This denotes and makes the URL replace the current page.
 _top This denotes that the URL replaces any framesets that may be loaded.
 name This denotes the name of the window.

JavaScript Window Object Timeout Methods

setTimeout():

The setInterval() method of Window object is used to call a function or evaluate an expression at
specified intervals. The setTimeout() method of a window object performs in a similar manner. In
contrast to the setInterval() method, the setTimeout() method of window object is used to call a
function or evaluate an expression after a specified number of milliseconds. The setTimeout()
method helps schedule the expression or function for the time specified by the user. The function
given in arguments is called or the expression is evaluated after a specified number of
milliseconds given as argument in the setTimeout() method of window object.

General Syntax of the setTimeout() method of window object:

window.setTimeout(expression/function, milliseconds)

setTimeout() example:

<html>
<head>
<script type="text/javascript">
function exf()
{
exforsys.close()
}

</script>
</head>
<body>
exforsys = window.open('','','width=100,height=200')
exforsys.document.write("Example on setTimeout()
method!")
exforsys.setTimeout('exf()', 7000)

</body></html>

The window exforsys is closed after seven seconds. The setTimeout() method is applied to the
window exforsys with a parameter passed as function exf(). This performs the action of closing

WWW.VIDYARTHIPLUS.COM BATHUSHA
WWW.VIDYARTHIPLUS.COM
the window exforsys by the statement exforsys.close(). This is performed after 7 seconds
because the second parameter passed to the setTimeout() method is 7000 milliseconds.

clearTimeout():

If a user wishes to cancel the timeout set in the setTimeout() method, he or she can use the
clearTimeout() method of window object. The clearTimeout() method of a window object is used
to cancel a timeout set with the setTimeout() method.

General Syntax of the clearTimeout() method of window object:

window.clearTimeout(timeoutID)

The timeoutID given as argument in the clearTimeout() method is the ID that is declared or set
during the setTimeout() method.

<html>
<head>
<script type="text/javascript">
exforsys = setTimeout
("window.location='http://exforsys.com/test.html'",
5000); </script></head></html>

The above example sends the user to a new page test.html in exforsys.com after 5 seconds. The
setTimeout method calls the page after 5000 milliseconds or 5 seconds. The ID of the setTimeout
method is set to exforsys.

Using the clearTimeout() method of window object and the previous example to cancel the
timeout set in the setTimeout() method:

<html>
<head>
<script type="text/javascript">
clearTimeout (exforsys);

</script></head></html>

II. Location Object

It is used to open the URL in the window.

assign():

The assign method of location object is used for loading a new document.

General syntax of assign method of location Object:

location.assign(URL)

for example

WWW.VIDYARTHIPLUS.COM BATHUSHA
WWW.VIDYARTHIPLUS.COM
<html>
<head>
<script type="text/javascript">
function test()
{
window.location.assign("http://www.exforsys.com")
}

</script>
</head>
<body>
<input type="button" value="Click Here For Loading New Document" onclick="test()" />

</body>
</html>

reload():

This method of location object is used for reloading the current document. The currently displayed
page in the window that owns the location object is reloaded. This means that the document that
owns the Location object is to be reloaded.

General syntax of reload method of location Object:

location.reload()

for example

<html>
<head>
<script type="text/javascript">
function test()
{
window.location.reload()
}

</script>
</head>
<body>
<input type="button" value="Click Here For ReLoading page" onclick="test()" />

</body>
</html>

replace():

As the name implies, the replace() method of location object replaces the current document with
a new one. The current History entry is replaced with the URL specified in the replace method.
NOTE: The programmer must know that after the replace method is called he or she cannot go
back to the previous URL by using the back button.

General syntax of replace method of location Object:

WWW.VIDYARTHIPLUS.COM BATHUSHA
WWW.VIDYARTHIPLUS.COM
location.replace(URL)

The URL specified in argument is the new URL.

for example

<html>
<head>
<script type="text/javascript">
function exareplace()
{
window.location.replace("http://www.exforsys.com")
}

</script>
</head>
<body>
<input type="button" value="Click Here to Replace" onclick="exareplace()" />

</body>
</html>

III.SCREEN OBJECT

The screen object contains information about the visitor's screen.

Screen Object Properties

Property Description
availHeight Returns the height of the screen (excluding the Windows Taskbar)
availWidth Returns the width of the screen (excluding the Windows Taskbar)
colorDepth Returns the bit depth of the color palette for displaying images
height Returns the total height of the screen
pixelDepth Returns the color resolution (in bits per pixel) of the screen
width Returns the total width of the screen

IV. Navigator Object

The navigator object contains information about the browser.

Navigator Object Properties

Property Description
appCodeName Returns the code name of the browser
appName Returns the name of the browser
appVersion Returns the version information of the browser
cookieEnabled Determines whether cookies are enabled in the browser
platform Returns for which platform the browser is compiled

WWW.VIDYARTHIPLUS.COM BATHUSHA
WWW.VIDYARTHIPLUS.COM
userAgent Returns the user-agent header sent by the browser to the server

Navigator Object Methods

Method Description
javaEnabled() Specifies whether or not the browser has Java enabled
taintEnabled() Specifies whether or not the browser has data tainting enabled

V.History Object

The history object contains the URLs visited by the user (within a browser window).

The history object is part of the window object and is accessed through the window.history
property.

History Object Properties

Property Description
length Returns the number of URLs in the history list

History Object Methods

Method Description
back() Loads the previous URL in the history list
forward() Loads the next URL in the history list
go() Loads a specific URL from the history list

An example to understand the back method of history object:

<html>
<head>
<script type="text/javascript">
function funback()
{
window.history.back()
}

</script>
</head>
<body><form>
<input type="button" value="Press the Button to go
to Previous Page!!!" onclick="funback()" /> </form>

</body></html>

VI.Document Object

Each HTML document loaded into a browser window becomes a Document object.

WWW.VIDYARTHIPLUS.COM BATHUSHA
WWW.VIDYARTHIPLUS.COM
The Document object provides access to all HTML elements in a page, from within a script.

Any document can contain various HTML Objects like

 Images
 ImageMaps
 Hyperlinks
 Frames
 Anchors
 Applets
 Mutimedia Objects
 Form with various elements

The browser creates one array per HTML object thus registering each HTML Objects.

The JavaScript arrays are

Image/Images array
Link/Links Array
Area
Frame/Frames Array
Anchor/Anchors array
Applet/Applets Array
Embed/Embeds Array
MimeType/MimeTypes array
Plugin/plugins array
Form/Forms array

Document Object Collections

W3C: W3C Standard.

Collection Description W3C


anchors[] Returns an array of all the anchors in the document Yes
forms[] Returns an array of all the forms in the document Yes
images[] Returns an array of all the images in the document Yes
links[] Returns an array of all the links in the document Yes

Document Object Properties

Property Description W3C


cookie Returns all name/value pairs of cookies in the document Yes
documentMode Returns the mode used by the browser to render the document No
domain Returns the domain name of the server that loaded the Yes
document
lastModified Returns the date and time the document was last modified No
readyState Returns the (loading) status of the document No
referrer Returns the URL of the document that loaded the current Yes

WWW.VIDYARTHIPLUS.COM BATHUSHA
WWW.VIDYARTHIPLUS.COM
document
title Sets or returns the title of the document Yes
URL Returns the full URL of the document Yes

Document Object Methods

Method Description W3C


close() Closes the output stream previously opened with Yes
document.open()
getElementById() Accesses the first element with the specified id Yes
getElementsByName() Accesses all elements with a specified name Yes
getElementsByTagName() Accesses all elements with a specified tagname Yes
open() Opens an output stream to collect the output from Yes
document.write() or document.writeln()
write() Writes HTML expressions or JavaScript code to a document Yes
writeln() Same as write(), but adds a newline character after each Yes
statement

Event HANDLING

Events are actions that can be detected by JavaScript, and the event object gives information
about the event that has occurred.

Sometimes we want to execute a JavaScript when an event occurs, such as when a user clicks a
button.

Events are normally used in combination with functions, and the function will not be executed
before the event occurs!

Javascript event handlers are divided into2 types

1. Interactive event handlers- depends on user interactin with the HTML page ex.
Clicking a button
2. Non-Interactive event handlers-does not need user interaction. Ex. onload

Event Attributes

Below is the event attributes that can be inserted into different HTML elements to define event
actions.

IE: Internet Explorer, F: Firefox, O: Opera, W3C: W3C Standard.

Attribute The event occurs when... IE F O W3C


onblur An element loses focus 3 1 9 Yes
onchange The content of a field changes 3 1 9 Yes
onclick Mouse clicks an object 3 1 9 Yes
ondblclick Mouse double-clicks an object 4 1 9 Yes

WWW.VIDYARTHIPLUS.COM BATHUSHA
WWW.VIDYARTHIPLUS.COM
onerror An error occurs when loading a document or an 4 1 9 Yes
image
onfocus An element gets focus 3 1 9 Yes
onkeydown A keyboard key is pressed 3 1 No Yes
onkeypress A keyboard key is pressed or held down 3 1 9 Yes
onkeyup A keyboard key is released 3 1 9 Yes
onload A page or image is finished loading 3 1 9 Yes
onmousedown A mouse button is pressed 4 1 9 Yes
onmousemove The mouse is moved 3 1 9 Yes
onmouseout The mouse is moved off an element 4 1 9 Yes
onmouseover The mouse is moved over an element 3 1 9 Yes
onmouseup A mouse button is released 4 1 9 Yes
onresize A window or frame is resized 4 1 9 Yes
onselect Text is selected 3 1 9 Yes
onunload The user exits the page 3 1 9 Yes

Mouse / Keyboard Attributes

Property Description IE F O W3C


altKey Returns whether or not the "ALT" key was pressed 6 1 9 Yes
when an event was triggered
button Returns which mouse button was clicked when an 6 1 9 Yes
event was triggered
clientX Returns the horizontal coordinate of the mouse 6 1 9 Yes
pointer when an event was triggered
clientY Returns the vertical coordinate of the mouse pointer 6 1 9 Yes
when an event was triggered
ctrlKey Returns whether or not the "CTRL" key was pressed 6 1 9 Yes
when an event was triggered
metaKey Returns whether or not the "meta" key was pressed 6 1 9 Yes
when an event was triggered
relatedTarget Returns the element related to the element that No 1 9 Yes
triggered the event
screenX Returns the horizontal coordinate of the mouse 6 1 9 Yes
pointer when an event was triggered
screenY Returns the vertical coordinate of the mouse pointer 6 1 9 Yes
when an event was triggered
shiftKey Returns whether or not the "SHIFT" key was pressed 6 1 9 Yes
when an event was triggered

Other Event Attributes

Property Description IE F O W3C


bubbles Returns a Boolean value that indicates whether or No 1 9 Yes

WWW.VIDYARTHIPLUS.COM BATHUSHA
WWW.VIDYARTHIPLUS.COM
not an event is a bubbling event
cancelable Returns a Boolean value that indicates whether or No 1 9 Yes
not an event can have its default action prevented
currentTarget Returns the element whose event listeners triggered No 1 9 Yes
the event
eventPhase Returns which phase of the event flow is currently Yes
being evaluated
target Returns the element that triggered the event No 1 9 Yes
timeStamp Returns the time stamp, in milliseconds, from the No 1 9 Yes
epoch (system start or event trigger)
type Returns the name of the event

Form Object

The Form object represents an HTML form.

For each <form> tag in an HTML document, a Form object is created.

Forms are used to collect user input, and contain input elements like text fields, checkboxes,
radio-buttons, submit buttons and more. A form can also contain select menus, textarea, fieldset,
legend, and label elements.

Forms are used to pass data to a server.

Form Object Collections

W3C: W3C Standard.

Collection Description W3C


elements[] Returns an array of all elements in a form Yes

The various form elements array are

Text, textarea, radio, checkbox, button, submit, reset, select, option, password,
hidden, fileupload

The HTML Form elements that can be specified in the <input>tag are

Form Elements Description/Syntax


Text A text field (<input type=”text”>)
Password A text field in which the keystroke appears as *

<input type=”password”>
Button A button other than a submit/reset button

<input type=”button”>
Checkbox A check box <input type=”checkbox”>
Radio A radio button<input type=”radio”>
Reset A Reset Button <input type=”reset”>
WWW.VIDYARTHIPLUS.COM BATHUSHA
WWW.VIDYARTHIPLUS.COM
Submit A submit button<input type=”submit”>
Select A selection list < select> <option>option1</option>

<option>option2</option>

</select>
Textarea A multiline textentry field <textarea> Default text </textarea>
Hidden A field that may contain a value but is not displayed within a
form <input type=”hidden”>

******Give sample prgms given in class for each of the FORM elements….. ************

Some of the properties of FORM elements are

Name - Indicates the name of an element.

Value - Indicates the current value of the element.

DefaultValue - Indicates the default value of the element.

Checked - Indicates the current status of the element.

DefaultChecked - Indicates the default status of the element

Length - Indicates the numberof elements in a group.

Some of the methods of form elements are

onFocus() - fires when a form cursor enters into the object.

Onblur() - fires when the form cursor is moved away from the object.

Onselect() - Fires when the text is selected in an object.

Onchange() - Fires when the text is changed in an object.

onClick() - Fires when an object is clicked on.

Form Object Properties

Property Description W3C


acceptCharset Sets or returns the value of the accept-charset attribute in a form Yes
action Sets or returns the value of the action attribute in a form Yes
enctype Sets or returns the value of the enctype attribute in a form Yes
length Returns the number of elements in a form Yes
method Sets or returns the value of the method attribute in a form Yes
name Sets or returns the value of the name attribute in a form Yes

WWW.VIDYARTHIPLUS.COM BATHUSHA
WWW.VIDYARTHIPLUS.COM
target Sets or returns the value of the target attribute in a form Yes

Form Object Methods

Method Description W3C


reset() Resets a form Yes
submit() Submits a form Yes

Form Object Events

Event The event occurs when... W3C


onreset The reset button is clicked Yes
onsubmit The submit button is clicked Yes

BUILT IN OBJECTS(NATIVE OBJECTS)

Date Object

The Date object is used to work with dates and times.

Date objects are created with new Date().

There are four ways of instantiating a date:

var d = new Date();


var d = new Date(milliseconds);
var d = new Date(dateString);
var d = new Date(year, month, day, hours, minutes, seconds, milliseconds);

Date Object Properties

Property Description
constructor Returns the function that created the Date object's prototype
prototype Allows you to add properties and methods to an object

Date Object Methods

Method Description
getDate() Returns the day of the month (from 1-31)
getDay() Returns the day of the week (from 0-6)
getFullYear() Returns the year (four digits)
getHours() Returns the hour (from 0-23)

WWW.VIDYARTHIPLUS.COM BATHUSHA
WWW.VIDYARTHIPLUS.COM
getMilliseconds() Returns the milliseconds (from 0-999)
getMinutes() Returns the minutes (from 0-59)
getMonth() Returns the month (from 0-11)
getSeconds() Returns the seconds (from 0-59)
getTime() Returns the number of milliseconds since midnight Jan 1, 1970
getTimezoneOffset() Returns the time difference between GMT and local time, in minutes
getUTCDate() Returns the day of the month, according to universal time (from 1-31)
getUTCDay() Returns the day of the week, according to universal time (from 0-6)
getUTCFullYear() Returns the year, according to universal time (four digits)
getUTCHours() Returns the hour, according to universal time (from 0-23)
getUTCMilliseconds() Returns the milliseconds, according to universal time (from 0-999)
getUTCMinutes() Returns the minutes, according to universal time (from 0-59)
getUTCMonth() Returns the month, according to universal time (from 0-11)
getUTCSeconds() Returns the seconds, according to universal time (from 0-59)
getYear() Deprecated. Use the getFullYear() method instead
parse() Parses a date string and returns the number of milliseconds since
midnight of January 1, 1970
setDate() Sets the day of the month (from 1-31)
setFullYear() Sets the year (four digits)
setHours() Sets the hour (from 0-23)
setMilliseconds() Sets the milliseconds (from 0-999)
setMinutes() Set the minutes (from 0-59)
setMonth() Sets the month (from 0-11)
setSeconds() Sets the seconds (from 0-59)
setTime() Sets a date and time by adding or subtracting a specified number of
milliseconds to/from midnight January 1, 1970
setUTCDate() Sets the day of the month, according to universal time (from 1-31)
setUTCFullYear() Sets the year, according to universal time (four digits)
setUTCHours() Sets the hour, according to universal time (from 0-23)
setUTCMilliseconds() Sets the milliseconds, according to universal time (from 0-999)
setUTCMinutes() Set the minutes, according to universal time (from 0-59)
setUTCMonth() Sets the month, according to universal time (from 0-11)
setUTCSeconds() Set the seconds, according to universal time (from 0-59)
setYear() Deprecated. Use the setFullYear() method instead
toDateString() Converts the date portion of a Date object into a readable string
toGMTString() Deprecated. Use the toUTCString() method instead
toLocaleDateString() Returns the date portion of a Date object as a string, using locale
conventions
toLocaleTimeString() Returns the time portion of a Date object as a string, using locale
conventions

WWW.VIDYARTHIPLUS.COM BATHUSHA
WWW.VIDYARTHIPLUS.COM
toLocaleString() Converts a Date object to a string, using locale conventions
toString() Converts a Date object to a string
toTimeString() Converts the time portion of a Date object to a string
toUTCString() Converts a Date object to a string, according to universal time
UTC() Returns the number of milliseconds in a date string since midnight of
January 1, 1970, according to universal time
valueOf() Returns the primitive value of a Date object

Math Object

The Math object allows you to perform mathematical tasks.

Math is not a constructor. All properties/methods of Math can be called by using Math as an
object, without creating it.

Syntax

var x = Math.PI; // Returns PI


var y = Math.sqrt(16); // Returns the square root of 16

Math Object Properties

Property Description
E Returns Euler's number (approx. 2.718)
LN2 Returns the natural logarithm of 2 (approx. 0.693)
LN10 Returns the natural logarithm of 10 (approx. 2.302)
LOG2E Returns the base-2 logarithm of E (approx. 1.442)
LOG10E Returns the base-10 logarithm of E (approx. 0.434)
PI Returns PI (approx. 3.14159)
SQRT1_2 Returns the square root of 1/2 (approx. 0.707)
SQRT2 Returns the square root of 2 (approx. 1.414)

Math Object Methods

Method Description
abs(x) Returns the absolute value of x
acos(x) Returns the arccosine of x, in radians
asin(x) Returns the arcsine of x, in radians
atan(x) Returns the arctangent of x as a numeric value between -PI/2 and PI/2
radians
atan2(y,x) Returns the arctangent of the quotient of its arguments
ceil(x) Returns x, rounded upwards to the nearest integer
cos(x) Returns the cosine of x (x is in radians)

WWW.VIDYARTHIPLUS.COM BATHUSHA
WWW.VIDYARTHIPLUS.COM
exp(x) Returns the value of Ex
floor(x) Returns x, rounded downwards to the nearest integer
log(x) Returns the natural logarithm (base E) of x
max(x,y,z,...,n) Returns the number with the highest value
min(x,y,z,...,n) Returns the number with the lowest value
pow(x,y) Returns the value of x to the power of y
random() Returns a random number between 0 and 1
round(x) Rounds x to the nearest integer
sin(x) Returns the sine of x (x is in radians)
sqrt(x) Returns the square root of x
tan(x) Returns the tangent of an angle

String Object

The String object is used to manipulate a stored piece of text.

String objects are created with new String().

Syntax

var txt = new String(string);

or more simply:

var txt = string;

String Object Properties

Property Description
constructor Returns the function that created the String object's prototype
length Returns the length of a string
prototype Allows you to add properties and methods to an object

String Object Methods

Method Description
charAt() Returns the character at the specified index
charCodeAt() Returns the Unicode of the character at the specified index
concat() Joins two or more strings, and returns a copy of the joined strings
fromCharCode() Converts Unicode values to characters
indexOf() Returns the position of the first found occurrence of a specified value in a
string
lastIndexOf() Returns the position of the last found occurrence of a specified value in a
string

WWW.VIDYARTHIPLUS.COM BATHUSHA
WWW.VIDYARTHIPLUS.COM
match() Searches for a match between a regular expression and a string, and returns
the matches
replace() Searches for a match between a substring (or regular expression) and a
string, and replaces the matched substring with a new substring
search() Searches for a match between a regular expression and a string, and returns
the position of the match
slice() Extracts a part of a string and returns a new string
split() Splits a string into an array of substrings
substr() Extracts the characters from a string, beginning at a specified start position,
and through the specified number of character
substring() Extracts the characters from a string, between two specified indices
toLowerCase() Converts a string to lowercase letters
toUpperCase() Converts a string to uppercase letters
valueOf() Returns the primitive value of a String object

Number Object

The Number object is an object wrapper for primitive numeric values.

Number objects are created with new Number().

Syntax

var num = new Number(value);

Note: If the value parameter cannot be converted into a number, it returns NaN (Not-a-Number).

Number Object Properties

Property Description
constructor Returns the function that created the Number object's prototype
MAX_VALUE Returns the largest number possible in JavaScript
MIN_VALUE Returns the smallest number possible in JavaScript
NEGATIVE_INFINITY Represents negative infinity (returned on overflow)
POSITIVE_INFINITY Represents infinity (returned on overflow)
prototype Allows you to add properties and methods to an object

Number Object Methods

Method Description
toExponential(x) Converts a number into an exponential notation

WWW.VIDYARTHIPLUS.COM BATHUSHA
WWW.VIDYARTHIPLUS.COM
toFixed(x) Formats a number with x numbers of digits after the decimal point
toPrecision(x) Formats a number to x length
toString() Converts a Number object to a string
valueOf() Returns the primitive value of a Number object

COOKIES

A cookie, also known as a web cookie, browser cookie, and HTTP cookie, is a piece
of text stored on a user's computer by their web browser. A cookie can be used for
authentication, storing site preferences, shopping cart contents, the identifier for a server-based
session, or anything else that can be accomplished through storing text data.

Cookies are small amounts of data stored by the web browser. They allow you to store particular
information about a user and retrieve it every time they visit your pages. Each user has their own
unique set of cookies.

Cookies are typically used by web servers to perform functions such as tracking your visits to
websites, enabling you to log in to sites, and storing your shopping cart.

A cookie consists of one or more name-value pairs containing bits of information, which
may be encrypted for information privacy and data security purposes. The cookie is sent as a
field in the header of the HTTP response by a web server to a web browser and then sent back
unchanged by the browser each time it accesses that server.

Cookies may be set by the server with or without an expiration date. Cookies without an
expiration date exist until the browser terminates, while cookies with an expiration date may be
stored by the browser until the expiration date passes. Users may also manually delete cookies in
order to save space or to avoid privacy issues.

As text, cookies are not executable. Because they are not executed, they cannot
replicate themselves and are not viruses. However, due to the browser mechanism to set and
read cookies, they can be used as spyware. Anti-spyware products may warn users about some
cookies because cookies can be used to track computer activity—a privacy concern, later
causing possible malware.

TYPES OF COOKIES

Session cookie

A session cookie only lasts for the duration of users using the website. A session cookie will
expire if a user closes his/her browser, or if a user hasn't visited the server for certain period of
time (called session idle timeout), and the server would expire/invalidate the user session.

Persistent cookie

A persistent cookie will outlast user sessions. If a persistent cookie has Max-Age set to 1 year,
then, within the year, the initial value set in that cookie would be sent back to server every time
the user is visiting the server. This could be used to record a vital piece of information such as
how the user initially came to this website. For this reason, persistent cookie is also called
tracking cookie.

WWW.VIDYARTHIPLUS.COM BATHUSHA
WWW.VIDYARTHIPLUS.COM
Secure cookie

A secure cookie is only used when a browser is visiting a server via HTTPS, that will make sure
that cookie is always encrypted when transmitting from client to server, and therefore less likely to
be exposed to cookie theft via eavesdropping.

HttpOnly cookie

HttpOnly cookie is still in IETF draft, though most of the modern browsers support it. On a
supported browser, a HttpOnly cookie will only be used when transmitting HTTP (or HTTPS)
requests, but the cookie value is not available to client side script, hence mitigate the threat of
cookie theft via Cross-site scripting.

Third-party cookie

First-party cookies are cookies set with the same domain or its subdomain in your browser's
address bar. Third-party cookies are cookies being set with different domains than the one shown
on address bar.

Super cookie

A Super cookie is a cookie with a Public Suffix domain, like .com, .co.uk or k12.ca.us.

Zombie cookie

A zombie cookie is any cookie that is automatically recreated after a user has deleted it. This is
accomplished by a script storing the content of the cookie in some other location, such as the
local storage available to Flash content, and then recreating it from the backup when the cookie's
absence is detected.

Setting a cookie

Transfer of Web pages follows the HyperText Transfer Protocol (HTTP). Regardless of cookies,
browsers request a page from web servers by sending them a usually short text called HTTP
request. For example, to access the page http://www.example.org/index.html, browsers connect
to the server www.example.org sending it a request that looks like the following one:

GET /index.html HTTP/1.1


Host: www.example.org
browser -------→ server

The server replies by sending the requested page preceded by a similar packet of text, called
'HTTP response'. This packet may contain lines requesting the browser to store cookies:

HTTP/1.1 200 OK
Content-type: text/html
Set-Cookie: name=value
Set-Cookie: name2=value2; Expires=Wed, 09 Jun 2021 10:18:14 GMT

(content of page)
browser ←------- server

WWW.VIDYARTHIPLUS.COM BATHUSHA
WWW.VIDYARTHIPLUS.COM

The server sends lines of Set-Cookie only if the server wishes the browser to store cookies. Set-
Cookie is a directive for the browser to store the cookie and send it back in future requests to the
server (subject to expiration time or other cookie attributes), if the browser supports cookies and
cookies are enabled.

The following are false:

 Cookies are like viruses in that they can infect the user's hard disks
 Cookies generate pop-ups
 Cookies are used for spamming
 Cookies are used only for advertising

The document.cookie property

Cookies in JavaScript are accessed using the cookie property of the document object. In simple

terms, we create a cookie like this:

Setting a cookie

To set a cookie, we set the document.cookie property to a string containing the properties of the

cookie that we want to create:

document.cookie = "name=value; expires=date; path=path; domain=domain; secure";

These properties are explained in the table below:

Property Description Example

name=value This sets both the cookie's name and its value. username=matt

This optional value sets the date that the cookie will

expire on. The date should be in the format returned


expires=
expires=date by the toGMTString() method of the Date object. If the
13/06/2003 00:00:00
expires value is not given, the cookie will be destroyed

the moment the browser is closed.

This optional value specifies a path within the site to


path=path path=/tutorials/
which the cookie applies. Only documents in this path

WWW.VIDYARTHIPLUS.COM BATHUSHA
WWW.VIDYARTHIPLUS.COM

will be able to retrieve the cookie. Usually this is left

blank, meaning that only the path that set the cookie

can retrieve it.

domain=domain This optional value specifies a domain within which domain=elated.com

the cookie applies. Only websites in this domain will

be able to retrieve the cookie. Usually this is left blank,

meaning that only the domain that set the cookie can

retrieve it.

secure This optional flag indicates that the browser should secure

use SSL when sending the cookie to the server. This

flag is rarely used.

Example

document.cookie = "username=John;

expires=15/02/2003 00:00:00";

This code sets a cookie called username, with a value of "John", that expires on Feb 15th, 2003

This code does exactly the same thing as the previous example, but specifies the date using the

Date.toGMTString() method instead. Note that months in the Date object start from zero, so

February is 01.

A function to delete a cookie

Another useful cookie-handling function is provided below. This function will "delete" the supplied

cookie from the browser by setting the cookie's expiry date to one second in the past.

function delete_cookie ( cookie_name )

WWW.VIDYARTHIPLUS.COM BATHUSHA
WWW.VIDYARTHIPLUS.COM
{

var cookie_date = new Date ( ); // current date & time

cookie_date.setTime ( cookie_date.getTime() - 1 );

document.cookie = cookie_name += "=; expires=" + cookie_date.toGMTString();

To use this function, just pass in the name of the cookie you would like to delete - for example:

delete_cookie ( "username" );

Retrieving cookies

To retrieve all previously set cookies for the current document, you again use the

document.cookie property: var x=document.cookie;

(Write the lab program using cookies)

WWW.VIDYARTHIPLUS.COM BATHUSHA

You might also like