0% found this document useful (0 votes)
144 views42 pages

User Defined Functions: Syntax

User defined functions allow programmers to declare reusable blocks of code to perform tasks. Functions are declared using the function keyword followed by a name and parameters. Functions can accept arguments, perform tasks, and return values. JavaScript provides built-in functions and methods to output text to the browser, accept user input, and display dialog boxes like alerts, prompts, and confirmations. The Document Object Model (DOM) represents the webpage and allows JavaScript to programmatically access and modify elements in an HTML document.

Uploaded by

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

User Defined Functions: Syntax

User defined functions allow programmers to declare reusable blocks of code to perform tasks. Functions are declared using the function keyword followed by a name and parameters. Functions can accept arguments, perform tasks, and return values. JavaScript provides built-in functions and methods to output text to the browser, accept user input, and display dialog boxes like alerts, prompts, and confirmations. The Document Object Model (DOM) represents the webpage and allows JavaScript to programmatically access and modify elements in an HTML document.

Uploaded by

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

User defined functions

A user defined function first needs to be declared and coded.

Once this is done the function can be invoked by calling it

using the name given to the function when it was declared.

Functions can accept information in the form of arguments

and can return results.

Declaring Functions

Functions are declared and created using the function

keyword. A function can comprise of the following:

 A name for the function

 A list of parameters

 A block of javascript code that defines what the function

does

Syntax:

function function_name(parameter1, parameter2){

//Block of JavaScript code

}
A function_name is case sensitive, can include underscores

and has to start with a letter.

Place of Declaration

Functions can be declared anywhere within an HTML file.

Functions are created within the <HEAD>…</HEAD> tags

of the HTML file. This ensures that all functions will be

parsed before they are invoked or called.

Passing parameters

Values can be passed to the function parameters when a

parameterized function is called. Values are passed to the

function by listing them in the parenthesis following the

function name. Multiple values can be passed, separated by

commas provided that the function has been coded to accept

multiple parameters.

Both Javascript built-in functions and user defined functions

can accept parameters, process them and return values. During


declaration, a function needs to be informed about the number

of values that will be passed.

Example:

function printName(user){

document.write(“<HR>Your Name is <B><I>”);

document.write(user);

document.write(“</B></I><HR>”);

Recursive Functions

Recursion refers to a situation wherein functions call

themselves. In other words, there is a call to a specific

function from within the same function. Such functions are

known as recursive functions.

Example:

function factorial(number){

if(number > 1){

return number * factorial(number-1);


}

else{

return number;}}

Example program

<HTML>

<HEAD>

<TITLE>CREATING AND USING USER DEFINED

FUNCTIONS</TITLE>

<SCRIPT Language="JavaScript">

var name="";

function hello(){

name=prompt('Enter Your name:', 'Name');

alert('Greetings' + name + ', Welcome to my page!');

function goodbye(){

alert('Good bye' + name + ', Sorry to see you go!');

}
</SCRIPT>

</HEAD>

<BODY onLoad="hello();" onUnload="goodbye();">

<P><H1>WELCOME TO JAVASCRIPT </H1>

</BODY>

</HTML>

Output
Placing text in a browser

Using Javascript a string can be written to the browser from

within an HTML file. The document object in javascript has a

method for placing text in a browser. This method is called

write(). Methods are called by combining the object name

with the method name:

Objectname.Method_name

The write() method accepts a string value passed to it within

its parenthesis. The string value can then be written to the

browser. The write() method accepts this string and places it

in the current browser window. For example,

document.write(“Test”);

The string “Test” will be placed in the browser.

Example program

<HTML>

<HEAD>

<TITLE>Outputting text</TITLE></HEAD>
<BODY><CENTER><BR><BR>

<IMG Height=100 Src="C:\Users\KADHAR\Desktop\1.jpg"

Width=100>Silicon Chip Technologies<BR>

<SCRIPT Language ="JavaScript">

document.write("<BR><BR>");

document.write('<IMG Height=100

Src="C:\\Users\\KADHAR\\Desktop\\1.jpg" Width=100>');

document.write("<B>Silicon Chip Technologies</B><BR>");

</SCRIPT>

</CENTER>

</BODY>

</HTML>

Output
Dialog Boxes

JavaScript provides the ability to pickup user input or display

small amounts of text to the user by using dialog boxes. These

dialog boxes appear as separate windows and their content

depends on the information provided by the user. This content

is independent of the text in the HTML page containing the

JavaScript script and does not affect the content of the page in

any way.

There are three types of dialog boxes provided by JavaScript:

The Alert Dialog Box

The simplest way to direct small amounts of textual output to

a browser’s window is to use an alter dialog box. The


JavaScript alert() method takes a string as an argument and

displays an alert dialog box in the browser window when

invoked by appropriate JavaScript.

The alert dialog box displays the string passed to the alert()

method, as well as an ok button. The javascript and the

HTML program, in which this code snippet is held, will not

continue processing until the ok button is clicked.

The alert dialog box can be used to display a cautionary

message or display some information. For instance:

 A message is displayed to the user when incorrect

information is keyed in a form

 An invalid result is the output of a calculation

 A warning that a service is not available on a given

date/time

Syntax:

alert(“<Message>”);

Example:
alert(“Click OK to continue”);

Example Program

<HTML>

<HEAD>

<TITLE>Alert Example </TITLE></HEAD>

<BODY><SCRIPT Language="JavaScript">

alert("Welcome to Department of Information Technology!");

document.write('<IMG

Src="C:\\Users\\KADHAR\\Desktop\\1.jpg">');

</SCRIPT>

</BODY>

</HTML>

Output
The Prompt Dialog Box

The prompt() method instantiates the prompt dialog box

which displays a specified message. In addition, the prompt

dialog box also provides a single data entry field, which

accepts user input. Thus a prompt dialog box:

 Displays a predefined message

 Displays a text box and accepts user input

 Can pass what the user keyed into the textbox back to the

javascript

 Displays the ok and the cancel buttons.

The prompt dialog box also causes program execution to halt

until user action takes place. This could be the ok button being

clicked, or the cancel button being clicked, which causes the

following action to take place.

 Clicking on the ok button causes the text typed inside the

text box to be passed to the program environment


 Clicking on the cancel button causes a null value to be

passed to the environment.

When the prompt() method is used to instantiate and use a

dialog box the method requires two blocks of information:

 A message to be displayed as a prompt to the user

 Any message to be displayed in the text box

Syntax

prompt(“<Message>”,”<Default value>”);

Example

prompt(“Enter your favorite color”,”Blue”);

Example program

<HTML>

<HEAD>

<TITLE>Prompt Example </TITLE></HEAD>

<BODY><SCRIPT Language="JavaScript">

document.write('<IMG

Src="C:\\Users\\KADHAR\\Desktop\\1.jpg">');
document.write("<H1>Greetings,");

document.write(prompt("Enter your name:","Name"));

document.write("<BR>Welcome to the Department of

Information Technology!</H1>");

</SCRIPT>

</BODY>

</HTML>

Output
The Confirm Dialog Box

JavaScript provides a third type of a dialog box, called the

confirm dialog box. As the name suggests, this dialog box

serves as a technique for confirming user action. The confirm

dialog box displays the following information:

 A pre-defined message

 Ok and cancel button

The confirm dialog box, causes program execution to halt

until user action takes place. User action can be either ok

button being clicked or the cancel button being clicked, which

causes the following action to take place.


 Clicking on the ok button causes true to be passed to the

program which called the confirm dialog box.

 Clicking on the cancel button causes false to be passed to

the program which called the confirm dialog box.

Syntax:

confirm(“<Message>”);

Example:

confirm(“Are you sure want to exit out of the system”);

Example Program

<HTML>

<HEAD>

<TITLE>Confirm Method</TITLE>

<SCRIPT Language="JavaScript">

var question="What is 10+10?";

var answer=20;

var correct='<IMG

Src="C:\\Users\\KADHAR\\Desktop\\1.jpg">';
var incorrect='<IMG

Src="C:\\Users\\KADHAR\\Desktop\\2.jpg">';

var Response = prompt(question,"0");

for(count=1;count<3;count++)

if(Response != answer)

if(confirm("Wrong, Press Ok for another chance"))

Response =prompt(question,"0");

else

alert("Better luck next time");

count=3;

}
else

alert("Great! you are right");

count=3;

var output=(Response == answer) ? correct : incorrect;

document.write("<BR>");

document.write(output);

</SCRIPT>

</HEAD>

<BODY></BODY>

</HTML>

Output
JavaScript DOM introduction

An HTML page is rendered in a browser. The browser

assembles all the elements contained in the HTML page,

downloaded from the web server, in its memory. Once done

the browser then renders these objects in the browser window.

Once the HTML page is rendered in the browser window, the

browser can no longer recognize individual HTML elements.


Javascript enabled browsers are capable of recognizing

individual objects in an HTML page, after the page has been

rendered in the browser, because the javascript enabled

browser recognizes and uses the document object model.

Using the Document Object Model javascript enabled

browsers identify the collection of web page objects that have

to be dealt with while rendering an HTML based, web page in

the browser window.

The HTML objects which belong to the DOM, have a

descending relationship with each other.

The topmost object in the DOM is the navigator itself. The

next level in the DOM is the browser’s window. The next

level in the DOM is the document displayed in the browser’s

window.

The DOM hierarchy continues downward to encompass

individual elements on a FORM, such as text boxes, labels,


radio buttons, check boxes, push buttons and so on which

belong to the form.

Javascript’s object hierarchy is mapped to the DOM, which in

turn is mapped to the web page elements in the browser

window. Hence, when a web page is rendered in a javascript

enabled browser window. Javascript is capable of uniquely

identifying each element in the web page, because major

elements of a web page are bound to the DOM.

The DOM that javascript recognizes is described in the figure

Instance
No HTML object is registered in the DOM by a javascript

enabled browser unless they are assembled in memory prior

being rendered in the browser window. What this means is, if

a document does not have any Anchors described in it the

Anchors object will exist but it will be empty. If the document

does not have any links described in it the links object will

exist but it will be empty.

Hierarchy

All objects on a web page are not created equal. Each exists in

a set relationship with other objects on the web page. From

the figure, the navigator occupies the topmost slot in the

DOM followed by the window object and so on.

Below the window is the document object. Below the

document object three other objects exist. They are Anchor,

Link and Form objects. Individual form elements are found

under the form object.


In addition to the DOM, other objects currently recognized by

a javascript enabled browser are plug-ins, applets and images.

Hence using a javascript enabled browser and javascript most

of the major web page objects are accessible.

However, every single element of a web page rendered in the

browser window, is not part of the DOM.

For example, HTML tags such as <head>…</head> or

<body>….</body> are not part of the DOM. Presentation

styles, headings, body text, H1 to H6 and so on are not part of

the DOM hence not recognized by Javascript.

Javascript however, recognizes presentation styles, headings,

body text, H1 to H6 and so on, when Javascript assisted style

sheets are in a web page. JSSS is usually between the

<head>….</head> HTML tags in a web page.

Javascript assisted Style Sheets DOM


JSSS use javascript syntax to control a document’s

presentation style. When a JSSS is embedded in an HTML

page within the <head>…</head> tags, then the javascript

DOM picks up a whole new set of objects, which add to the

standard DOM objects already recognized by javascript. By

extending the DOM recognized by javascript by embedding

JSSS in a web page, developers of web pages can access

every element of a web page whether this element appears on

the page when it is rendered in a client browser or not.

By accessing appropriate properties of the Navigator object,

the topmost object in the DOM, javascript can recognize the

browser type and subsequently dispatch all HTML pages to

the browser from the web server, with a style based on this

knowledge. This is where the power of javascript really

becomes visible in providing finely tuned web page content to

a client’s browser.
Since javascript understands the DOM and can extend the

DOM with the use of JSSS in a web page javascript

understands objects.

All objects have

 Properties that determine the functionality of the object

 Methods that allow access to these properties

 Events that allow javascript code snippets to be

connected to the object by being mapped to appropriate

javascript event handlers.

Hence when a predetermined event occurs the code snippet

will execute. This is the traditional object, event driven, code

execution model of any object based programming

environment.

Using appropriate javascript code snippets, which reference

the properties of an object via its built-in methods, developers


of web pages can actually control the functionality of any

HTML object in the DOM while the HTML program

executes.

Javascript can access the methods of all objects belonging to

the DOM and the JSSS DOM. Hence, using javascript, truly

interactive web pages can be created.

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. It is the DOM, which provides

javascript access to the HTML objects that are contained in

the web page.

The javascript code snippets imbedded as part of the web page

itself make use of these objects to interact with the HTML

objects in the web page.


The javascript objects created by Netscape Communicator are

listed below:

Object Name Its use

Navigator To access information about the browser that

is executing the current script

Windows To access a browser window or a frame

within the window

Document To access the document currently loaded

into a window

Location To represent a URL. It can be used to create

a URL object, access parts of a URL, or

modify an existing URL

History To maintain the history of the URL’s

accessed within a window


Event To access information about the occurrence

of an event

EVENT The EVENT object provides constants that

are used to identify events

Screen To access information about the size and

color depth of a client computer’s screen in

which the current browser is running

How a javascript enabled browser handles the document

object

Any document can contain various HTML objects such as

 Images

 Image maps

 Hyperlinks

 Frames
 Anchors

 Applets

 Multimedia objects such as audio files, streaming video

files

 A form with various form elements

The browser creates one array in memory per HTML object in

the document, thus registering each of these HTML objects.

If these HTML objects are actually contained in the HTML

page then these arrays will hold indexed elements, which will

point to the context area in the memory where the HTML

object are. Otherwise, the array will exist, but will be empty.

If there are multiple, similar HTML objects in the document

each array will have multiple elements.

The array index value mapped to an HTML object will

correspond to where the HTML object was described in the


document. The first image in the document will have the array

index as [0], the next image in the document will have the

array index of [1] and so on.

Javascript provides access to the arrays and their elements.

The values of any/all elements of each array can be identified,

obtained. The values held in the elements of these arrays point

to the context area in memory where the HTML objects

actually are.

Once the context area in memory of an HTML object is

known then using the Methods of the object, specific object

Properties can be set using javascript. Thus the functionality

of an HTML object can be controlled while the HTML page is

running in the browser.

The javascript arrays created by netscape communicator are

listed below:
Image/Images array To access an image that is embedded

in an HTML document. The images

array is used to access all image

objects in a document

Link/Links Array To access a text or image based

source anchor of a hypertext link.

The links array is used to access all

link objects within a document

Area To access an area within a client side

image map

Frame/Frames Array To access an HTML frame. The

frames array is used to access all

frames within a window

Anchor/Anchors Array To access the target of a hyperlink.

The anchors array is used to access


all anchor objects within a document

Applet/Applets Array To access a java applet. The applets

array being used to access all the

applets in a document

Embed/Embeds Array To access an embedded object. The

embeds array provides access to all

the embedded objects in a document

MimeType/MimeTypes To access information about a

Array particular MIME type supported by a

browser. The mimetypes array is an

array of all the mimetype objects

supported by a browser

Plugin/Plugins array To access information about a

particular browser plug-in. The

plugins array is an array of all plug-


ins supported by a browser

Form/Forms array To access an HTML form. The

forms array is used to access all

forms within a document

The javascript form elements array created by netscape

communicator

Elements Access to all the form elements in the form

Text To access a text field of a form

Textarea To access a text area of a form

Radio To access a set of radio button on the form or

to access an individual radio button within the

set

Checkbox To access a checkbox on a form


Button To access a form button that is not a reset or

submit button

Submit To access a submit button on a form

Reset To access a reset button on a form

Select To access a select list of a form

Option The option object is used to access the

elements of a select list

Password To access a password field on a form

Hidden To access a hidden object on a form

Fileupload To access a file upload element of a form

The web page HTML object hierarchy

This is an instance hierarchy. This means if a web page does

not have a specific HTML object defined in it the array

associated with that specific HTML object will exist, but will

have no elements.
Access to elements of a web page

Conceptually once a web page is rendered in a browser

window it is completely static. For any program code to be

able to interact with the web page, each element of the web

page would have to be held in memory, with a unique name.

The unique name translates to a context area in memory

where the web page element resides.

Hence, while a web page is being assembled in memory prior

being rendered in the browser’s window, a javascript enabled

browser creates several arrays as described earlier. These

arrays hold references to individual web page objects in their

elements.

Referencing an appropriate element in its associated array

provides access to each element of a web page. Hence, using

javascript web page elements can be updated or processed.

Once processed, the web page can be re-rendered in the


browser. When re-rendered in the browser changes made to

the web page elements will be visible.

How a web page element is manipulated

HTML tags are used to create objects in a web page. For

example, <input type=”text”> will instantiate a text box on

the web page when encountered in HTML code.

Each HTML object instantiated in a web page has properties

and methods that allow access to the object’s properties. Each

HTML object has an event or several events bound to the

object when the object was created. Thus an HTML object

can recognize a specific event when it occurs.

Once the HTML object recognizes that an event has occurred

this knowledge has to be passed to javascript so that javascript

also recognizes that the event occurred. To facilitate this

javascript provides a number of named javascript event


handlers. The names of these event handlers are descriptively

bound to an HTML object’s event name.

Example

A change event is recognized by a text box when its contents

change. Javascript provides an event handler called onChange

that is internally bound to the change event of the text box.

The change event of the text box talks to the onChange event

handler of javascript. The onchange event handler of

javascript can then execute an appropriate javascript code

snippet. For examples

<input type=”text”onChange=”<myFunction>”>

Here the javascript function myFunction is bound to the

javascript event handler onChange. The assignment operator

(=) does this binding. The javascript onchange event handler,

is bound to the HTML object TEXT by being passed as one of


its attributes. Hence, as soon as the change event of the text

box occurs the javascript event handler onChange is invoked.

Since, the javascript function myFunction is bound to the

javascript event handler onChange, as soon as the onChange

event handler is invoked the javascript code in myFunction

executes.

Handling events using javascript

A web page event could be associated with the action of the

mouse cursor on the web page. Such as:

 A mouse click on an object in a web page

 The movement of the mouse cursor across a web page

 The mouse cursor hovering at a specific place on a web

page and so on

These will be events recognized by the window object of the

DOM.
Other web page events could be the opening or closing of a

window, the loading of an image in a web page and so on.

Javascript’s approach to working with web page elements is a

multistep process

Identify a web page object

Choose an appropriate event associated with the object

Have a standard method of connecting an object’s event and

javascript code snippets. Javascript event handlers mapped to

an object’s events do this.

Javascript has several named event handlers that are mapped

to an HTML object’s events. To work with javascript it is

necessary to understand how to use javascript ‘event handlers’

correctly.

Javascript event handlers, can be divided into two types

interactive and non-interactive.


An interactive event handler depends on user interaction with

an HTML page. For example, the javascript onMouseOver

event handler is an interactive event handler. This requires the

user to move the mouse cursor over a web page.

A javascript, non-interactive, event handler does not need user

interaction to be invoked. For example the javascript

‘onLoad’ event handler is a non-interactive event handler as it

automatically executes whenever a form is loaded into a web

page.

Named javascript event handlers

Javascript Event Will be called when

handler

onAbort The loading of an image is aborted as

a result of user action

onBlur A document, window, frameset, or


form element loses current input focus

onChange A text field, text area, file-uploaded

field or selection is modified and loses

the current input focus

onClick A link, client-side image map area or

document is clicked

onDblClick A link, client-side image map area or

document is double clicked

onDragDrop A dragged object is dropped in a

window or frame

onError An error occurs during loading of an

image, window or frame

onFocus A document, window, frameset, or

form element receives the current

input focus
onKeyDown The user presses a key

onKeyPress The user presses and releases a key

onKeyUp The user releases a key

onLoad An image, document or frameset is

loaded

onMouseDown The user processes a mouse button

onMouseMove The user moves the mouse

onMouseOut The mouse is moved out of a link or an

area of a client side image map

onMouseOver The mouse is moved over a link or an

area of a client side image map

onMouseUp The user releases a mouse button

onReset The user resets a form by clicking on

the form’s reset button


onResize The user resizes a window or frame

onSelect Text is selected in a text field or a text

area

onSubmit The user presses a form’s submit

button

onUnload The user exits a document or frameset

You might also like