JavaScript Client-Side Programming Guide
JavaScript Client-Side Programming Guide
JavaScript is the programming language of HTML and the Web, Also called as Client-Side Scripting
Language designed to add interactivity to HTML pages.
It is a Client-side script to interact with the user and make dynamic pages.
JavaScript was first known as LiveScript, but Netscape changed its name to JavaScript, possibly
because of the excitement being generated by Java.
Features of JavaScript
JavaScript is an open source scripting language.
It is lightweight.
It creates network-centric applications.
It is platform independent.
It validates form data.
It reduces server load.
What can a JavaScript do?
JavaScript can put dynamic text into an HTML page
JavaScript can react to events - A JavaScript can be set to execute when
something happens, like when a page has finished loading or when a user clicks
on an HTML element
JavaScript can read and write HTML elements - A JavaScript can read and
change the content of an HTML element
JavaScript can be used to validate data - A JavaScript can be used to validate form
data before it is submitted to a server. This saves the server from extra processing
JavaScript can be used to create cookies - A JavaScript can be used to store
and retrieve information on the visitor's computer
Advantages of JavaScript
JavaScript saves server traffic.
It performs the operations very fast.
It is simple to learn and implement.
It is versatile.
JavaScript pages are executed on the client side.
JavaScript extends its functionality to the web pages.
Disadvantages of JavaScript
JavaScript cannot be used for networking applications.
It doesn't have any multithreading or multiprocessor capabilities.
It has security issues being a client-side scripting language.
What is a script?
Script is a small, embedded program.
The most popular scripting languages on the web are, JavaScript orVBScript.
HTML does not have scripting capability, you need to use <script> tag.
The <script> tag is used to generate a script.
The </script> tag indicates the end of the script or program.
1
Example : Type attribute
<script type = “text/javascript”> [Link](“TutorialRide”);
</script>
The 'type' attribute indicates which script language you are using withthe type
attribute.
Example : Language attribute
<script language= “javascript”> [Link](“TutorialRide”);
</script>
You can also specify the <script language> using the 'language'
attribute.
Types of Scripts
1. Client-Side Scripting
2. Server-Side Scripting
Client-Side Scripting
Client-Side Scripting is an important part of the Dynamic HTML(DHTML).
JavaScript is the main client-side scripting language for the web.
The scripts are interpreted by the browser.
Client-Side scripting is used to make changes in the web page afterthey arrive at
the browser.
It is useful for making the pages a bit more interesting and user-friendly.
2
Server-Side Scripting is used to provide interactive web sites.
It is different from Client-Side Scripting where the scripts are run by viewing the web browser,
usually in JavaScript.
It is used for allowing the users to have individual accounts andproviding data
from databases.
It allows a level of privacy, personalization and provision of
information that is very useful.
It includes [Link] and PHP.
It does not rely on the user having specific browser or plug-in.
It is affected by the processing speed of the host server.
4
Rules for writing the JavaScript code:
Script should be placed inside the <script> tag.
A semicolon at the end of each statement is optional.
The single line comment is just two slashes (//) and multiple linecomment starts
with /* and ends with */.
Use '[Link]' for writing a string into HTML document.
JavaScript is case sensitive.
You can insert special characters with backslash (\& or \$).
Displaying Output in JavaScript
JavaScript Display Possibilities : JavaScript can "display" data indifferent
ways:
o Writing into an HTML element, using innerHTML.
o Writing into the HTML output using [Link]().
o Writing into an alert box, using [Link]().
o Writing into the browser console, using [Link]().
Example:
<html>
<body>
<h2>My First Web Page</h2>
<p>My First Paragraph.</p>
<p id="demo"></p>
<script>
[Link]("demo").innerHTML = 5 + 6;
[Link](10 + 10)
[Link](10 + 30);
[Link](10 + 40);
</script>
</body>
</html>
Alert Box
An alert box is often used if you want to make sure information comesthrough
to the user.
When an alert box pops up, the user will have to click "OK" toproceed.
Syntax; [Link]("sometext");
5
Confirm Box
A confirm box is often used if you want the user to verify or acceptsomething.
When a confirm box pops up, the user will have to click either "OK" or"Cancel"
to proceed.
If the user clicks "OK", the box returns true. If the user clicks"Cancel", the
box returns false.
Syntax: [Link]("sometext");
Prompt Box
A prompt box is often used if you want the user to input a valuebefore entering
a page.
When a prompt box pops up, the user will have to click either "OK" or"Cancel"
to proceed after entering an input value.
If the user clicks "OK" the box returns the input value. If the userclicks
"Cancel" the box returns null.
Syntax: [Link]("sometext","defaultText");
2) If – Else Statement
If – Else is a two-way decision statement.
It is used to make decisions and execute statements conditional
Flow Diagram of If – Else Statement
<html>
<head>
<script type="text/javascript">
var no = prompt("Enter a Number to find Odd or Even");no =
parseInt(no);
if (isNaN(no))
9
{
alert("Please Enter a Number");
}
else if (no == 0)
{
alert("The Number is Zero");
}
else if (no % 2)
{
alert("The Number is Odd");
}
else
{
alert("The Number is Even");
}
</script>
</head>
</html>
Output
3) Switch Statement
Switch is used to perform different actions on different conditions.
It is used to compare the same expression to several different values.
Flow Diagram of Switch Statement
10
Example : Simple Program for Switch Statement
<html>
<head>
<script type="text/javascript">
var day = prompt("Enter a number between 1 and 7");switch
(day)
{
case (day="1"):
[Link]("Sunday");
break;
case (day="2"):
[Link]("Monday");
break;
case (day="3"):
[Link]("Tuesday");
break;
case (day="4"):
[Link]("Wednesday"); break;
case (day="5"):
[Link]("Thursday");break;
case (day="6"):
[Link]("Friday"); break;
case (day="7"):
[Link]("Saturday");break;
default:
[Link]("Invalid Weekday");
break;
}
</script>
</head>
</html>
Output:
4) For Loop
For loop is a compact form of looping.
It includes three important parts:
1. Loop Initialization
2. Test Condition
3. Iteration
11
All these three parts come in a single line separated by semicolons(;).
Flow Diagram of 'For' Loop
12
5) For-in Loop
For-in loop is used to traverse all the properties of an object.
It is designed for looping through arrays.
Syntax
for (variable_name in Object)
{
//Statements;
}
6) While Loop
While loop is an entry-controlled loop statement.
It is the most basic loop in JavaScript.
It executes a statement repeatedly as long as expression is true.
Once the expression becomes false, the loop terminates.
var i = 0;
do
{
[Link](i+"<br>") i++;
}
while (i <= 5)
</script>
</body>
</html>
Output:
0
1
2
3
4
5
Difference between While Loop and Do – While Loop
While Loop Do – While Loop
In while loop, first it checks the In Do – While loop, first it executes the
condition and then executes the program and then checks the condition.
program.
It is an entry – controlled loop. It is an exit – controlled loop.
The condition will come before the The condition will come after the body.
body.
If the condition is false, then it It runs at least once, even though the
14
terminates the loop. conditional is false.
It is a counter-controlled loop. It is a iterative control loop.
8) Break Statement
Break statement is used to jump out of a loop.
It is used to exit a loop early, breaking out of the enclosing curly braces.
Flow Diagram of Break Statement
9) Continue Statement
Continue statement causes the loop to continue with the next iteration.
It skips the remaining code block.
Flow Diagram of Continue Statement
Syntax
do
{
//Statements;
}
15
JavaScript Built-in Functions
JavaScript provides number of built-in functions.
Common Built-in Functions
Functions Description
isNan() Returns true, if the object is Not a Number.
Returns false, if the object is a number.
parseFloat If the string begins with a number, the function reads throughthe string
(string) until it finds the end of the number; cuts off the remainder of the string and
returns the result.
If the string does not begin with a number, the function returnsNaN.
parseInt If the string begins with an integer, the function reads throughthe string
(string) until it finds the end of the integer, cuts off the remainder of the string and
returns the result.
If the string does not begin with an integer, the function returnsNaN (Not
a Number).
String Converts the object into a string.
(object)
eval() Returns the result of evaluating an arithmetic expression.
User-defined Functions
User-defined function means you can create a function for your own use. Youcan
create yourself according to your need.
In JavaScript, these functions are written in between the <HEAD> tag of the
HTML page.
JavaScript Function Syntax
function keyword --- followed by a name ---- followed by parentheses().
Function names can contain letters, digits, underscores, and dollarsigns
(same rules as variables).
The parentheses may include parameter names separated by commas:
(parameter1, parameter2, ...)
The code to be executed, by the function, is placed inside curlybrackets: {}
Syntax:
function name(parameter1, parameter2, parameter3)
{
// code to be executed
}
Example :
function myFunction(p1, p2)
{
return p1 * p2; // The function returns the product of p1 and p2
}
Function Invocation
The code inside the function will execute when "something" invokes(calls) the
function:
When an event occurs (when a user clicks a button)
When it is invoked (called) from JavaScript code
16
Automatically (self invoked)
Function Return
When JavaScript reaches a return statement, the function will stopexecuting.
If the function was invoked from a statement, JavaScript will "return"to
execute the code after the invoking statement.
Functions often compute a return value. The return value is "returned"back to the
"caller―.
Example:
Example:
<html>
<head>
<script>
function toCelsius(f) { var
res=(5/9) * (f-32);
[Link](f+ " Degree Fahrenheit is = "+[Link](res,2)+" Degree Celsius");
}
</script>
</head>
<body>
<h2>JavaScript Functions</h2>
<button onclick='toCelsius(98);'>Click Here</button>
</body>
</html>
</html>
At the top level, there is an html node, with two children: head andbody, among which only head
has a child tag title.
HTML tags are element nodes in DOM tree, pieces of text become textnodes.
Both of them are nodes, just the type is different.
19
ACCESSING DOM:
The HTML DOM can be accessed with JavaScript (and with otherprogramming
languages).
In the DOM, all HTML elements are defined as objects.
With the object model, JavaScript gets all the power it needs to createdynamic
HTML:
JavaScript can change all the HTML elements in the page
JavaScript can change all the HTML attributes in the page
JavaScript can change all the CSS styles in the page
JavaScript can remove existing HTML elements and attributes
JavaScript can add new HTML elements and attributes
JavaScript can react to all existing HTML events in the page
JavaScript can create new HTML events in the page
Types of nodes
There are many types of nodes in the DOM document tree that specifies what kind of
node it is. Every Object in the DOM document tree has properties and methods defined
by the Node host object.
The following table lists the non method properties of Node object.
The following table lists the node types commonly encountered in HTMLdocuments and
the nodeType value for each one.
20
The following table lists the method properties of Node object.
21
[Link](text) Write into the HTML output stream
Adding Events Handlers
Method Description
Adding event handler
[Link](id).onclick=function(){code} code to an onclick event
Reacting to Events
A JavaScript can be executed when an event occurs, like when a userclicks on
an HTML element.
To execute code when a user clicks on an element, add JavaScriptcode to
an HTML event attribute:
onclick=JavaScript
Examples of HTML events:
When a user clicks the mouse
When a web page has loaded
When an image has been loaded
When the mouse moves over an element
Example:
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">var
page_element=""; function end()
{
var txt=[Link]("end of document");[Link](txt);
}
function Display() // function definition
{
for(i=0;i<[Link];i++)
{
page_element+="<br>"+[Link][i].tagName; // accessing all the
elements using DOM
}
[Link]="center"; // accessing element's atrribute
[Link]+=page_element;// setting the element's text
}
</script>
</head>
<body onload="Display()">
<p class="exp">Example for Accessing Elements</p>
<div id="main">
<p>The DOM is very useful.</p>
<p id="demo"></p>
</div>
<p class="exp">Thank You</p>
<script>
var x = [Link]("main");var y =
[Link]("p"); y[1].innerHTML =
"Welcome DOM";
22
var z=[Link]("exp");
z[0].[Link]="blue";
z[1].[Link]="Green";
</script>
<p id="pmsg" > <strong> Various Elements used in this web documentsare:</strong></p>
<button id="btn" value="click me" onClick="end()">Click Me</button>
</body></html>
function validate(){
var name = [Link];var
email = [Link];
var username = [Link];var
24
password = [Link];var
gender = [Link];
var errors = [];
if (!ck_name.test(name)) {
errors[[Link]] = "Enter your valid Name ."; }
if (!ck_email.test(email)) {
errors[[Link]] = "You must enter a valid email address.";
}
if (!ck_username.test(username)) {
errors[[Link]] = "You must enter valid UserName with no specialchar .";
}
if (!ck_password.test(password)) {
errors[[Link]] = "You must enter a valid Password min 6 char.";
}
if (gender==0) {
errors[[Link]] = "Select Gender";
}
if ([Link] > 0) {
reportErrors(errors); return
false;
}
return true;
}
function reportErrors(errors){
var msg = "Please Enter Valide Data...\n";for (var
i = 0; i<[Link]; i++) {
var numError = i + 1;
msg += "\n" + numError + ". " + errors[i];
}
alert(msg);
}
</script>
</head>
<body>
<center> REGISTRATION FORM</center> <hr>
<form action="[Link]" name="form">
<label> Full Name </label>
<input type="text" name="name" value="" /> <br><br>
<label> Email Id </label>
<input type="text" name="email" value="" /> <br><br>
<label> Username </label>
<input type="text" name="username" value="" /> <br><br>
<label> Password </label>
<input type="text" name="password" value="" /> <br><br>
<label> Gender </label>
<select name="gender">
<option value="0">Gender</option>
<option value="1">Female</option>
<option value="2">Male</option>
</select> <br><br>
25
<input type="submit" value="Submit" onclick="return validate()">
</form>
</body>
</html>
31
log() Returns the natural logarithm (base E) of a number.
max() Returns the largest of zero or more numbers.
min() Returns the smallest of zero or more numbers.
pow() Returns base to the exponent power, that is base exponent.
Example: Simple Program on Math Object Methods
<html>
<head>
<title>JavaScript Math Object Methods</title>
</head>
<body>
<script type="text/javascript">
var value = [Link](20);
[Link]("ABS Test Value : " + value +"<br>");
var value = [Link](-1);
[Link]("ACOS Test Value : " + value +"<br>");
var value = [Link](1);
[Link]("ASIN Test Value : " + value +"<br>");
var value = [Link](.5);
[Link]("ATAN Test Value : " + value +"<br>");
</script>
</body>
</html>
Output
ABS Test Value : 20
ACOS Test Value : 3.141592653589793
ASIN Test Value : 1.5707963267948966
ATAN Test Value : 0.4636476090008061
2) Date Object
Date is a data type.
Date object manipulates date and time.
Date() constructor takes no arguments.
Date object allows you to get and set the year, month, day, hour,minute, second
and millisecond fields.
Syntax: var variable_name = new Date();
Example: var current_date = new Date();
Date Methods
Methods Description
Date() Returns current date and time.
getDate() Returns the day of the month.
getDay() Returns the day of the week.
getFullYear() Returns the year.
getHours() Returns the hour.
getMinutes() Returns the minutes.
getSeconds() Returns the seconds.
getMilliseconds() Returns the milliseconds.
getTime() Returns the number of milliseconds since January 1,1970 at 12:00
AM.
32
getTimezoneOffset() Returns the timezone offset in minutes for the currentlocale.
getMonth() Returns the month.
setDate() Sets the day of the month.
setFullYear() Sets the full year.
setHours() Sets the hours.
setMinutes() Sets the minutes.
setSeconds() Sets the seconds.
setMilliseconds() Sets the milliseconds.
setTime() Sets the number of milliseconds since January 1, 1970at 12:00 AM.
setMonth() Sets the month.
toDateString() Returns the date portion of the Date as a human- readable string.
toLocaleString() Returns the Date object as a string.
toGMTString() Returns the Date object as a string in GMT timezone.
valueOf() Returns the primitive value of a Date object.
Example : JavaScript Date() Methods Program
<html>
<body>
<center>
<h2>Date Methods</h2>
<script type="text/javascript">var d
= new Date();
[Link]("<b>Locale String:</b> " +[Link]()+"<br>");
[Link]("<b>Hours:</b> " + [Link]()+"<br>");
[Link]("<b>Day:</b> " + [Link]()+"<br>");
[Link]("<b>Month:</b> " + [Link]()+"<br>");
[Link]("<b>FullYear:</b> " + [Link]()+"<br>");
[Link]("<b>Minutes:</b> " + [Link]()+"<br>");
</script>
</center>
</body>
</html>
Output:
String Object
String objects are used to work with text.
It works with a series of characters.
Syntax: var variable_name = new String(string);
Example:
var s = new String(string);
33
String Properties
Properties Description
length It returns the length of the string.
prototype It allows you to add properties and methods to an object.
constructor It returns the reference to the String function that created theobject.
String Methods
Methods Description
charAt() It returns the character at the specified index.
charCodeAt() It returns the ASCII code of the character at the specifiedposition.
concat() It combines the text of two strings and returns a new string.
indexOf() It returns the index within the calling String object.
match() It is used to match a regular expression against a string.
replace() It is used to replace the matched substring with a newsubstring.
search() It executes the search for a match between a regularexpression.
slice() It extracts a session of a string and returns a new string.
split() It splits a string object into an array of strings by separatingthe
string into the substrings.
toLowerCase() It returns the calling string value converted lower case.
toUpperCase() Returns the calling string value converted to uppercase.
Example : JavaScript String() Methods Program
<html>
<body>
<center>
<script type="text/javascript"> var
str = "CareerRide Info"; var s =
[Link]();
[Link]("<b>Char At:</b> " + [Link](1)+"<br>");
[Link]("<b>CharCode At:</b> " +
[Link](2)+"<br>");
[Link]("<b>Index of:</b> " + [Link]("ide")+"<br>");
[Link]("<b>Lower Case:</b> " +
[Link]()+"<br>");
[Link]("<b>Upper Case:</b> " +
[Link]()+"<br>");
</script>
<center>
</body>
</html>
Output:
Boolean Object
The Boolean object is used to convert a non-Boolean value to aBoolean value
(true or false).
34
Syntax
Use the following syntax to create a boolean [Link] val =
new Boolean(value);
Boolean Object Methods
Method Description
toString() Converts a Boolean value to a string, and returns the result
valueOf() Returns the primitive value of a Boolean object
Number Object
The Number object is an object wrapper for primitive numeric [Link]
objects are created with new Number().
Syntax :var num = new Number(value);
Properties of Number object
Constructor - Returns the function that created the Number object.
MAX VALUE - Returns maximum numerical value possible in
JavaScript.
MIN VALUE - Returns minimum numerical value possible in
JavaScript.
NEGATIVE INFINITY - Represent the value of negative infinity.
POSITIVE INFINITY - Represent the value of infinity.
Prototype - Add properties and methods to an object.
Number Object Methods
Method Description
toExponential(x) Converts a number into an exponential notation
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
toLocaleString() - Returns a string value version of the current number in a
format that may vary according to a browser's localesettings.
Example:
<!DOCTYPE html>
<html>
<head>
<title>JavaScript toPrecision() Method </title>
</head>
<body>
<script type = "text/javascript">
var num = new Number(7.123456);
[Link]("Maximum Value " + Number.MAX_VALUE);[Link]("<br />");
[Link]("Minimum Value " + Number.MIN_VALUE);[Link]("<br />");
[Link]("[Link](4) is " + [Link](4));[Link]("<br />");
[Link]("[Link](4) is : " + [Link](4));[Link]("<br />");
</script>
</body>
</html>
35
5) W i n d ow O b je ct
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 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
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
Example : Simple Program on User-defined Function
<html>
<body>
<script type="text/javascript">
function add() // Function Declaration
{
var a = 2,b = 3;
var sum = 0;
sum = a+b;
[Link]("<b>Addition: </b>"+sum);
}
</script>
<p> Click the Button</p>
<input type="button" onClick="add()" value="Click"> //add() -
Calling Function
</body>
</html>
Output:
36
2.6 DHTML (DYNAMIC HYPERTEXT MARKUP LANGUAGE)
function change_Color(newColor) {
var element = [Link]('demo').[Link] = newColor;
}
</script>
</body>
</html>
38
2.7 JSON introduction – Syntax
JSON stands for Javascript Object Notation. JSON is a text-based dataformat that is
used to store and transfer data.
For example,
// JSON syntax
{
"name": "John",
"age": 22,
"gender": "male",
}
In JSON, the data are in key/value pairs separated by a comma ,.
JSON was derived from JavaScript. So, the JSON syntax resembles JavaScript object
literal syntax. However, the JSON format can be accessed and be created by other
programming languages too.
JSON Syntax
The JSON syntax is a subset of the JavaScript syntax.
JSON Syntax Rules
JSON syntax is derived from JavaScript object notation syntax:
Data is in name/value pairs.
The name-value pairs are grouped by a colon (:) and separated by acomma (,)
Data is separated by commas
Curly braces hold objects
Square brackets hold arrays
An array begins with a left bracket and ends with a right bracket []
Each key within the JSON should be unique and should beenclosed within
the double quotes.
The boolean type matches only two special values: true and false and NULL
values are represented by the null literal (without quotes).
JSON Data - A Name and a Value
JSON data is written as name/value pairs.
A name/value pair consists of a field name (in double quotes), followedby a
colon, followed by a value.
JSON Values
In JSON, values must be one of the following data types:
a string
a number
an object (JSON object)
an array
a boolean
null
In JavaScript values can be all of the above, plus any other valid JavaScriptexpression,
including:
a function
39
date
undefined
Example
"name":"John"
JSON Object
JSON Array
JSON array is written inside square brackets . For example,
[]
// JSON array
[ "apple", "mango", "banana"]
"hobby": {
},
40
Though the syntax of JSON is similar to the JavaScript object, JSON is
different from JavaScript objects.
JSON JavaScript Object
The key in key/value pair should be in The key in key/value pair can be
double quotes. without double quotes.
JavaScript objects can contain
JSON cannot contain functions. functions.
JSON can be created and used by other JavaScript objects can only be
programming languages. used in JavaScript.
// JavaScript object
const jsonData = { "name": "John", "age": 22 };
myFunction(myArray);
3: Use an array literal as the argument (instead of the array variable):
myFunction([
{
"display": "JavaScript Tutorial",
"url": "[Link]
},
{
"display": "HTML Tutorial",
"url": "[Link]
},
{
"display": "CSS Tutorial",
"url": "[Link]
}
]);
4: Put the function in an external js file
Put the function in a file named [Link]:
42
myFunction([
{
"display": "JavaScript Tutorial",
"url": "[Link]
},
{
"display": "HTML Tutorial",
"url": "[Link]
},
{
"display": "CSS Tutorial",
"url": "[Link]
}
]);
Add the external script to your page (instead of the function call):
Add External Script
<script src="[Link]"></script>
43