You are on page 1of 100

WEB PROGRAMMING

Unit 3- JavaScript – Client Side Programming


TOPICS TO BE COVERED
INTRODUCTION TO JAVASCRIPT
 JavaScript is the most popular and widely used
client-side scripting language.
 Client-side scripting refers to scripts that run
within your web browser.
 JavaScript is designed to add interactivity and
dynamic effects to the web pages by
manipulating the content returned from a web
server.
 JavaScript is an object-oriented language, and it
also has some similarities in syntax to Java
programming language. But, JavaScript is not
related to Java in any way.
WHAT YOU CAN DO WITH JAVASCRIPT
 You can modify the content of a web page by adding
or removing elements.
 You can change the style and position of the elements
on a web page.
 You can monitor events like mouse click, hover, etc.
and react to it.
 You can perform and control transitions and
animations.
 You can create alert pop-ups to display info or
warning messages to the user.
 You can perform operations based on user inputs and
display the results.
 You can validate user inputs before submitting it to
the server.
WHY TO LEARN JAVASCRIPT
 JavaScript is the most popular programming
language in the world and that makes it a
programmer’s great choice. Once you learnt
JavaScript, it helps you developing great front-end as
well as back-end softwares.
 Javascript is everywhere, it comes installed on every
modern web browser and so to learn Javascript you
really do not need any special environment setup.
 Javascript helps you create really beautiful and crazy
fast websites.
 JavaScript usage has now extended to mobile app
development, desktop app development, and game
development.
JAVASCRIPT FRAMEWORKS
 There are many useful Javascript
frameworks and libraries available:
 Angular
 React
 jQuery
 Vue.js
 Ext.js
 Ember.js
 Meteor
 Mithril
 Node.js
 Polymer
 Aurelia
 Backbone.js
APPLICATIONS OF JAVASCRIPT
PROGRAMMING
 Client side validation - This is really important
to verify any user input before submitting it to the
server and Javascript plays an important role in
validting those inputs at front-end itself.
 Manipulating HTML Pages - Javascript helps
in manipulating HTML page on the fly. This helps
in adding and deleting any HTML tag very easily
using javascript and modify your HTML to change
its look and feel based on different devices and
requirements.
 User Notifications - You can use Javascript to
raise dynamic pop-ups on the webpages to give
different types of notifications to your website
visitors.
APPLICATIONS OF JAVASCRIPT
PROGRAMMING
 Back-end Data Loading - Javascript provides Ajax
library which helps in loading back-end data while you
are doing some other processing. This really gives an
amazing experience to your website visitors.
 Presentations - JavaScript also provides the facility
of creating presentations which gives website look and
feel. JavaScript provides RevealJS and BespokeJS
libraries to build a web-based slide presentations.
 Server Applications - Node JS is built on Chrome's
Javascript runtime for building fast and scalable
network applications. This is an event based library
which helps in developing very sophisticated server
applications including Web Servers.
ADDING JAVASCRIPT TO YOUR WEB PAGES
ADDING JAVASCRIPT TO YOUR WEB
PAGES
There are typically three ways to add JavaScript to
a web page:

1. Embedding the JavaScript code between a pair of


<script> and </script> tag.
2. Creating an external JavaScript file with the .js
extension and then load it within the page through
the src attribute of the <script> tag.
3. Placing the JavaScript code directly inside an
HTML tag using the special tag attributes such as
onclick, onmouseover, onkeypress, onload, etc.
1. EMBEDDING THE JAVASCRIPT CODE
 You can embed the JavaScript code directly within your
web pages by placing it between the <script> and
</script> tags. The <script> tag indicates the browser
that the contained statements are to be interpreted as
executable script and not HTML. Here's an example:
2. CALLING AN EXTERNAL JAVASCRIPT
FILE
 You can also place your JavaScript code into a separate
file with a .js extension, and then call that file in your
document through the src attribute of the <script> tag.
 This is useful if you want the same scripts available to
multiple documents.
Here's an example: Here hello.js is the JavaScript file-

Hello.js file code:

// A function to display a message


function sayHello()
{
alert("Hello World!");
}

// Call function on click of the button


document.getElementById("myBtn")
.onclick = sayHello;
3. PLACING THE JAVASCRIPT CODE
INLINE
 You can also place JavaScript code inline by inserting it
directly inside the HTML tag using the special tag
attributes such as onclick, onmouseover, onkeypress,
onload, etc.
 However, you should avoid placing large amount of
JavaScript code inline as it clutters up your HTML with
JavaScript and makes your JavaScript code difficult to
maintain. Here's an example:

 The above example will show you an alert message on click of the
button element.
DIFFERENCE BETWEEN CLIENT-SIDE AND
SERVER-SIDE SCRIPTING
DIFFERENCE BETWEEN CLIENT-SIDE
AND SERVER-SIDE SCRIPTING

 Client-side scripting languages are interpreted and


executed by the web browser, while server-side scripting
languages runs on the web server and the output sent
back to the web browser in HTML format.
 Client-side scripting has many advantages over
traditional server-side scripting approach.
 For example, you can use JavaScript to check if the user
has entered invalid data in form fields and show
notifications for input errors accordingly in real-time
before submitting the form to the web-server for final
data validation and further processing in order to
prevent unnecessary network bandwidth usages and the
exploitation of server system resources.
JAVASCRIPT SYNTAX
UNDERSTANDING THE JAVASCRIPT
SYNTAX
 The syntax of JavaScript is the set of rules that define a
correctly structured JavaScript program.
 A JavaScript consists of JavaScript statements that are
placed within the <script></script> HTML tags in a web
page, or within the external JavaScript file having .js
extension.
 The following example shows how JavaScript statements
look like:
UNDERSTANDING THE JAVASCRIPT
SYNTAX
 You can place the <script> tags, containing your
JavaScript, anywhere within your web page, but it is
normally recommended that you should keep it within
the <head> tags.
 The <script> tag alerts the browser program to start
interpreting all the text between these tags as a
script.
The script tag takes two important attributes −
 Language − This attribute specifies what scripting
language you are using. Typically, its value will be
javascript. Although recent versions of HTML (and
XHTML, its successor) have phased out the use of this
attribute.
 Type − This attribute is what is now recommended to
indicate the scripting language in use and its value
should be set to "text/javascript".
UNDERSTANDING THE JAVASCRIPT
SYNTAX
Whitespace and Line Breaks
 JavaScript ignores spaces, tabs, and newlines
that appear in JavaScript programs. You can use
spaces, tabs, and newlines freely in your program
and you are free to format and indent your
programs in a neat and consistent way that
makes the code easy to read and understand.
Semicolons are Optional
 Simple statements in JavaScript are generally
followed by a semicolon character, just as they
are in C, C++, and Java. JavaScript, however,
allows you to omit this semicolon if each of your
statements are placed on a separate line.
UNDERSTANDING THE JAVASCRIPT
SYNTAX
Case Sensitivity
 JavaScript is a case-sensitive language. This
means that the language keywords, variables,
function names, and any other identifiers must
always be typed with a consistent capitalization
of letters.
 So the identifiers Time and TIME will convey
different meanings in JavaScript.
COMMENTS IN JAVASCRIPT
 Any text between a // and the end of a line is
treated as a comment and is ignored by
JavaScript.
 Any text between the characters /* and */ is
treated as a comment. This may span multiple
lines.
 JavaScript also recognizes the HTML comment
opening sequence <!--. JavaScript treats this as a
single-line comment, just as it does the //
comment.
 The HTML comment closing sequence --> is not
recognized by JavaScript so it should be written
as //-->.
JAVASCRIPT - PLACEMENT IN HTML FILE
 There is a flexibility given to include JavaScript
code anywhere in an HTML document. However
the most preferred ways to include JavaScript in
an HTML file are as follows −
1. Script in <head>...</head> section
2. Script in <body>...</body> section
3. Script in <body>...</body> and
<head>...</head> sections
4. Script in an external file and then include in
<head>...</head> section.
JAVASCRIPT - VARIABLES
JAVASCRIPT - VARIABLES
 Like many other programming languages,
JavaScript has variables. Variables can be
thought of as named containers. You can place
data into these containers and then refer to the
data simply by naming the container.
 Before you use a variable in a JavaScript
program, you must declare it. Variables are
declared with the var keyword as follows.
JAVASCRIPT VARIABLE SCOPE
 The scope of a variable is the region of your program
in which it is defined. JavaScript variables have only
two scopes.
Global Variables − A global variable has global scope
which means it can be defined anywhere in your
JavaScript code.
Local Variables − A local variable will be visible only
within a function where it is defined. Function
parameters are always local to that function.
 Within the body of a function, a local variable takes
precedence over a global variable with the same
name. If you declare a local variable or function
parameter with the same name as a global variable,
you effectively hide the global variable.
JAVASCRIPT VARIABLE SCOPE
 Within the body of a function, a local variable takes
precedence over a global variable with the same name. If
you declare a local variable or function parameter with the
same name as a global variable, you effectively hide the
global variable.
JAVASCRIPT VARIABLE NAMES
 While naming your variables in JavaScript,
keep the following rules in mind.
 You should not use any of the JavaScript reserved
keywords as a variable name. These keywords are
mentioned in the next section. For
example, break or boolean variable names are not
valid.
 JavaScript variable names should not start with a
numeral (0-9). They must begin with a letter or an
underscore character. For example, 123test is an
invalid variable name but _123test is a valid one.
 JavaScript variable names are case-sensitive. For
example, Name and name are two different
variables.
JAVASCRIPT OPERATORS
JAVASCRIPT ARITHMETIC OPERATORS
JAVASCRIPT ASSIGNMENT OPERATORS
JAVASCRIPT COMPARISON OPERATORS
JAVASCRIPT LOGICAL OPERATORS
JAVASCRIPT - IF...ELSE
STATEMENT
JAVASCRIPT - IF...ELSE STATEMENT
 JavaScript supports the following forms
of if..else statement −
 if statement

 if...else statement

 if...else if... statement


IF STATEMENT
 The if statement is the fundamental control
statement that allows JavaScript to make
decisions and execute statements conditionally.
 Syntax−
IF STATEMENT
IF...ELSE STATEMENT

 The 'if...else' statement is the next form of


control statement that allows JavaScript to
execute statements in a more controlled way.
 Syntax-
IF...ELSE STATEMENT
IF...ELSE IF... STATEMENT

 The if...else if... statement is an advanced form


of if…else that allows JavaScript to make a
correct decision out of several conditions.
 Syntax-

 There is nothing special about this code. It is just a series


of if statements, where each if is a part of the else clause of the
previous statement. Statement(s) are executed based on the true
condition, if none of the conditions is true, then the else block is
executed.
IF...ELSE IF... STATEMENT
JAVASCRIPT - SWITCH CASE
JAVASCRIPT - SWITCH CASE
 The objective of a switch statement is to give an
expression to evaluate and several different statements to
execute based on the value of the expression. The
interpreter checks each case against the value of the
expression until a match is found. If nothing matches,
a default condition will be used.
JAVASCRIPT - SWITCH CASE
JAVASCRIPT - WHILE LOOPS
JAVASCRIPT - WHILE LOOPS
 The purpose of a while loop is to execute a statement
or code block repeatedly as long as an expression is
true. Once the expression becomes false, the loop
terminates.
JAVASCRIPT - WHILE LOOPS
Syntax
 The syntax of while loop in JavaScript is as
follows −
JAVASCRIPT - WHILE LOOPS
THE DO...WHILE LOOP
THE DO...WHILE LOOP
 The do...while loop is similar to the while loop
except that the condition check happens at the end of
the loop. This means that the loop will always be
executed at least once, even if the condition is false.
THE DO...WHILE LOOP
Syntax
 The syntax of do-while loop in JavaScript is as
follows −
THE DO...WHILE LOOP
JAVASCRIPT - FOR LOOP
JAVASCRIPT - FOR LOOP
 The 'for' loop is the most compact form of
looping. It includes the following three important
parts −
 The loop initialization where we initialize our
counter to a starting value. The initialization
statement is executed before the loop begins.
 The test statement which will test if a given
condition is true or not. If the condition is true,
then the code given inside the loop will be
executed, otherwise the control will come out of
the loop.
 The iteration statement where you can
increase or decrease your counter.
JAVASCRIPT - FOR LOOP
 The flow chart of a for loop in JavaScript would be as
follows −

 The syntax of for loop is JavaScript is as follows −


EXAMPLE
JAVASCRIPT - FUNCTIONS
JAVASCRIPT - FUNCTIONS
 A function is a group of reusable code which can
be called anywhere in your program.
 This eliminates the need of writing the same code
again and again.
 It helps programmers in writing modular codes.

 Functions allow a programmer to divide a big


program into a number of small and manageable
functions.
 JavaScript allows us to write our own functions
as well.
JAVASCRIPT - FUNCTIONS
 Before we use a function, we need to define it.
The most common way to define a function in
JavaScript is by using the function keyword,
followed by a unique function name, a list of
parameters (that might be empty), and a
statement block surrounded by curly braces.
 The basic syntax is shown here.
JAVASCRIPT - FUNCTIONS
 Example
 The following example defines a function called
sayHello that takes no parameters.
CALLING A FUNCTION
 To invoke a function somewhere later in the script,
you would simply need to write the name of that
function as shown in the following code.
FUNCTION PARAMETERS
 There is a facility to pass different parameters
while calling a function.
 These passed parameters can be captured inside
the function and any manipulation can be done
over those parameters.
A function can take multiple parameters
separated by comma.
FUNCTION PARAMETERS - EXAMPLE
 The function sayHello from previous example is
modified here. Now it takes two parameters.
THE RETURN STATEMENT
 A JavaScript function can have an
optional return statement.
 This is required if you want to return a value
from a function.
 This statement should be the last statement in a
function.
 For example, you can pass two numbers in a
function and then you can expect the function to
return their multiplication in your calling
program.
EXAMPLE
 Below example defines a function that takes two
parameters and concatenates them before returning the
resultant in the calling program.
JAVASCRIPT - EVENTS
JAVASCRIPT - EVENTS
 JavaScript's interaction with HTML is handled
through events that occur when the user or the
browser manipulates a page.
 When the page loads, it is called an event. When the
user clicks a button, that click too is an event. Other
examples include events like pressing any key, closing
a window, resizing a window, etc.
 Developers can use these events to execute JavaScript
coded responses, which cause buttons to close
windows, messages to be displayed to users, data to
be validated, and virtually any other type of response
imaginable.
 Events are a part of the Document Object Model
(DOM) Level 3 and every HTML element contains a
set of events which can trigger JavaScript Code.
<BODY> AND <FRAMESET> LEVEL
EVENTS
 There are only two attributes which can be used
to trigger any javascript or vbscript code when
there is any event occurs on document level.
<FORM> LEVEL EVENTS
 There are following six attributes which can be
used to trigger any javascript or vbscript code
when there is any event occurs on form level.
KEYBOARD EVENTS
 There are following three events which are
generated by keyboard. These events are not
valid in base, bdo, br, frame, frameset, head,
html, iframe, meta, param, script, style, and title
elements.
OTHER EVENTS
 There following other 7 events which are generated
by mouse when it comes in contact of any HTML tag.
These events are not valid in base, bdo, br, frame,
frameset, head, html, iframe, meta, param, script,
style, title elements.
JAVASCRIPT - DIALOG BOXES
JAVASCRIPT - DIALOG BOXES
 JavaScript supports three important types of
dialog boxes.
 These dialog boxes can be used to raise and alert,
or to get confirmation on any input or to have a
kind of input from the users.
ALERT DIALOG BOX
 An alert dialog box is mostly used to give a
warning message to the users.
 For example, if one input field requires to enter
some text but the user does not provide any
input, then as a part of validation, you can use an
alert box to give a warning message.
 Nonetheless, an alert box can still be used for
friendlier messages.
 Alert box gives only one button "OK" to select and
proceed.
ALERT DIALOG BOX - EXAMPLE
CONFIRMATION DIALOG BOX
 A confirmation dialog box is mostly used to take
user's consent on any option.
 It displays a dialog box with two
buttons: OK and Cancel.
 If the user clicks on the OK button, the window
method confirm() will return true.
 If the user clicks on the Cancel button,
then confirm() returns false.
CONFIRMATION DIALOG BOX - EXAMPLE
PROMPT DIALOG BOX
 The prompt dialog box is very useful when you want to
pop-up a text box to get user input. Thus, it enables you
to interact with the user. The user needs to fill in the
field and then click OK.
 This dialog box is displayed using a method
called prompt() which takes two parameters: (i) a label
which you want to display in the text box and (ii) a
default string to display in the text box.
 This dialog box has two buttons: OK and Cancel. If the
user clicks the OK button, the window
method prompt() will return the entered value from the
text box.
 If the user clicks the Cancel button, the window
method prompt() returns null.
PROMPT DIALOG BOX - EXAMPLE
JAVASCRIPT - THE ARRAYS
OBJECT
JAVASCRIPT - THE ARRAYS OBJECT
 The Array object lets you store multiple values
in a single variable.
 It stores a fixed-size sequential collection of
elements of the same type.
 An array is used to store a collection of data, but
it is often more useful to think of an array as a
collection of variables of the same type.
 Syntax:
JAVASCRIPT - THE ARRAYS OBJECT
 You will use ordinal numbers to access and to set
values inside an array as follows.
ARRAY PROPERTIES
JAVASCRIPT - THE DATE OBJECT
 The Date object is a datatype built into the JavaScript
language. Date objects are created with the new
Date( ) as shown below.
 Once a Date object is created, a number of methods
allow you to operate on it. Most methods simply allow
you to get and set the year, month, day, hour, minute,
second, and millisecond fields of the object, using
either local time or UTC (universal, or GMT) time.
JAVASCRIPT - DOCUMENT
OBJECT MODEL OR DOM
JAVASCRIPT - DOCUMENT OBJECT
MODEL OR DOM
 The HTML DOM is a standard object model
and programming interface for HTML. It
defines:
 The HTML elements as objects
 The properties of all HTML elements
 The methods to access all HTML elements
 The events for all HTML elements

 The way a document content is accessed and


modified is called the Document Object Model,
or DOM.
 The HTML DOM is a standard for how to
get, change, add, or delete HTML elements.
JAVASCRIPT - DOCUMENT OBJECT
MODEL OR DOM
 Window object − Top of the hierarchy. It is the
outmost element of the object hierarchy.
 Document object − Each HTML document that
gets loaded into a window becomes a document
object. The document contains the contents of the
page.
 Form object − Everything enclosed in the
<form>...</form> tags sets the form object.
 Form control elements − The form object
contains all the elements defined for that object
such as text fields, buttons, radio buttons, and
checkboxes.
THE DOM PROGRAMMING INTERFACE
 The HTML DOM can be accessed with
JavaScript (and with other programming
languages).
 In the DOM, all HTML elements are defined
as objects.
 The programming interface is the properties and
methods of each object.
 A property is a value that you can get or set
(like changing the content of an HTML element).
 A method is an action you can do (like add or
deleting an HTML element).
EXAMPLE
 The following example changes the content (the
innerHTML) of the <p> element with id="demo":
<html>
<body>
<p id="demo"></p>
<script>
document.getElementById("demo").innerHTML = "Hello World!";
</script>
</body>
</html>
 In the example above, getElementById is a
method, while innerHTML is a property.
THE DOM PROGRAMMING INTERFACE
 The getElementById Method
 The most common way to access an HTML element is
to use the id of the element.
 In the example above the getElementById method
used id="demo" to find the element.
 The innerHTML Property
 The easiest way to get the content of an element is by
using the innerHTML property.
 The innerHTML property is useful for getting or
replacing the content of HTML elements.
The innerHTML property can be used to get or
change any HTML element, including <html> and
<body>.
THE HTML DOM DOCUMENT OBJECT
 The document object represents your web page.
 If you want to access any element in an HTML page,
you always start with accessing the document object.
 Below are some examples of how you can use the
document object to access and manipulate HTML.
THE HTML DOM DOCUMENT OBJECT
JAVASCRIPT HTML DOM ELEMENTS
 Finding HTML Elements
 Often, with JavaScript, you want to manipulate
HTML elements.
 To do so, you have to find the elements first.
There are several ways to do this:
 Finding HTML elements by id
 Finding HTML elements by tag name
 Finding HTML elements by class name
 Finding HTML elements by CSS selectors
 Finding HTML elements by HTML object collections
JAVASCRIPT HTML DOM ELEMENTS
 Finding HTML Element by Id
 The easiest way to find an HTML element in the
DOM, is by using the element id. This example
finds the element with id="intro":

 If the element is found, the method will return


the element as an object (in element).
 If the element is not found, element will contain
null.
JAVASCRIPT HTML DOM ELEMENTS
 Finding HTML Elements by Tag Name
 This example finds all <p> elements:

 This example finds the element with id="main",


and then finds all <p> elements inside "main":
JAVASCRIPT - FORM
VALIDATION
JAVASCRIPT - FORM VALIDATION
 Form validation normally used to occur at the server,
after the client had entered all the necessary data and
then pressed the Submit button. If the data entered by
a client was incorrect or was simply missing, the server
would have to send all the data back to the client and
request that the form be resubmitted with correct
information. Form validation generally performs two
functions.
 Basic Validation − First of all, the form must be checked to
make sure all the mandatory fields are filled in. It would
require just a loop through each field in the form and check
for data.
 Data Format Validation − Secondly, the data that is
entered must be checked for correct form and value. Your
code must include appropriate logic to test correctness of
data.
JAVASCRIPT - FORM VALIDATION
 HTML form validation can be done by JavaScript.
 If a form field (fname) is empty, this function alerts a
message, and returns false, to prevent the form from being
submitted:

 The function can be called when the form is submitted:


JAVASCRIPT CAN VALIDATE NUMERIC
INPUT
DATA VALIDATION
 Data validation is the process of ensuring that user
input is clean, correct, and useful.
 Typical validation tasks are:
 has the user filled in all required fields?
 has the user entered a valid date?
 has the user entered text in a numeric field?
 Most often, the purpose of data validation is to ensure
correct user input.
 Validation can be defined by many different methods,
and deployed in many different ways.
 Server side validation is performed by a web
server, after input has been sent to the server.
 Client side validation is performed by a web
browser, before input is sent to a web server.
END..

You might also like