WEB PROGRAMMING
Chapter 3
Client Side Scripting (Java Script)
INTRODUCTION
JavaScript is a popular web-page scripting
language, and is supported by almost every
browser.
It adds interactivity to web technology pages.
JavaScript is usually embedded directly into HTML
pages
FEATURES OF JAVASCRIPT
It is lightweight, whose implementations allow
client-side script to interact with the user and
make dynamic pages.
It is interpreted programming language with
object-oriented capabilities.
Open and cross-platform (machine independent).
JavaScript is a case-sensitive language.
Sothe identifiers Time and TIME will convey different
meanings in JavaScript.
JavaScript is a client-side scripting language
that runs entirely inside the web browser.
BENEFITS OF JAVASCRIPT
Following are some of the benefits that
JavaScript language possesses to make the
website dynamic.
It is widely supported in browser.
It gives easy access to document object and
can manipulate most of them.
It can give interesting animations with many
multimedia data types.
It is secure language because it can detect the
visitor's browser.
It can react to events, read and write HTML
elements
It can be used to validate data
JAVASCRIPT RULES
JavaScript program contains variables, objects and
functions.
Each line is terminated by a semicolon.
Blocks of code must be surrounded by curly
brackets.
Functions have parameters which are passed
inside parenthesis.
Variables are declared using the keyword var.
Script does not require main function and exit
condition.
Language Format
JavaScript can be implemented using JavaScript
statements that are placed within the
<script>... </script> HTML tags in a web page.
You can place the <script> tags, containing your
JavaScript, anywhere within you 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.
So, syntax will look as follows:
<script language="javascript“ type= "text/ javascript
">
JavaScript code
</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 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".
Take a look at the following code.
<html> <body>
<script language="javascript"
type="text/javascript">
document.write ("Hello World!")
</script> </body> </html>
This code will produce the following result:
Hello World!
DESCRIPTION:
The <script type="text/javascript"> tag tells the
browser that whatever comes between that tag
and the coming </script> tag is script.
The type="text/javascript" tells it that it is
JavaScript.
The document.write() is the JavaScript standard
for writing text to the browser window.
The 'document' clause refers to the HTML
webpage (termed a document) as a whole;
what follows ('.write()') is a command for the
document object to carry out.
JavaScript variables
JavaScript is used for the manipulation of data. The
pieces of data can be stored either in variables or
arrays.
JavaScript Variables are declared using the “var”
keyword. Syntax: var num;
JavaScript variables can be declared with initial value.
Syntax: var num=1;
Multiple JavaScript variables can even be declared at
the same time.
Syntax: var num=1; var name= “Bikila”;
Every JavaScript variables ends with semicolon (;).
Variables in JavaScript are weakly typed, meaning that
the types of individual variables are not determined by
the programmer.
Unlike many languages, JavaScript only provides a
generic “var” rather than separate types for integers,
floating point numbers, characters, and strings.
Example: var x = 0; → x is a number
Data types and primitives
There are six data types in JavaScript:
1. Numbers: – Integer or floating point numbers
2. Booleans: – Either true/false or a number (0
being false) can be used for boolean values
3. Strings: – Sequence of characters enclosed in a
set of single or double quotes
4. Objects: – Entities that typically represents
elements of a HTML page
5. Null: – No value assigned which is different from
0
6. Undefined: – Is a special value assigned to an
identifier after it has been declared but before a
value has been assigned to it
JAVASCRIPT POPUP BOXES
• JavaScript has three kinds of popup boxes:
• Alert Box: - is used if you want to make sure
information comes through to the user.
• Syntax: alert("sometext");
CONFIRM BOX
Is used if you want the user to verify or accept
something.
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: confirm("sometext");
if (confirm("Press a button!")) {
txt = "You pressed OK!";
} else {
txt = "You pressed Cancel!";
}
PROMPT BOX
Is used if you want the user to input a value before
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 user clicks "Cancel" the box returns null.
Syntax: prompt("sometext","defaultvalue");
var person = prompt("Please enter your name",
"Nahil");
if (person == null || person == "") {
txt = "User cancelled the prompt.";
} else {
txt = "Hello " + person + "! How are you today?";
}
FUNCTIONS IN JAVASCRIPT
A function consists of the “function” keyword
followed by the name of the function, a set of
open and close parentheses enclosing an optional
parameter list and a body enclosed in a set of
curly braces.
Syntax: function
functionName(parameterList) {
// body
}
Function parameters are separated by commas in
the function declaration.
A function uses the return keyword to return a
value from a function.
JavaScript code found in a function is not executed
until the function is called.
Assigns function to event: - many elements of
DOM support events. These events are normally
the result of some user actions.
Example:
<html>
<body>
<script type="text/javascript">
function addition(){
var x=7;
var y=10;
var sum=x+y;
alert(sum);}
</script>
<form>
<input type="button" onclick="addition()"
value="show">
</form> </body></html>
OBJECTS IN JAVASCRIPT
JavaScript is not a pure object oriented
programming language, but uses the concept of
objects.
The new keyword used here is to create an
object, it allocates memory and storage.
Objects can have functions and variables.
To differentiate between global variables and
those which are part of an object but may have
the same name,
JavaScript uses this keyword.
When referring to a property of an object, whether
a
method or a variable, a dot is placed between the
object name and the property.
REGULAR EXPRESSION:
A script language may take name data from a
user and have to search through the string one
character at a time.
The usual approach in scripting language is to
create a pattern called a regular expression
which describes a set of characters that may be
present in a string.
The regular expression can be shown below.
var pattern = new RegExp(“target”);
var string = “can you find the target”;
pattern.test(string);
Regular expression is a javascript object.
Dynamic patterns are created using the keyword
new.
regex = new RegExp(“feroz | amer”);
JavaScript code to implement RegExp
<html> <head> <title> registration form</title>
<script type="text/javascript">
function v() {
var a=document.f.un.value;
var b=document.f.pw.value;
var r1=new RegExp("^[a-zA-Z]{6,}$");
var r2=new RegExp("^[a-zA-Z0-9]{6,}$");
if(r1.test(a)) {
if(r2.test(b)) {
window.alert("ur successfully login"); }
else
window.alert("enter password atleast 6 characters
"); }
else {
window.alert("enter uname atleast 6 characters and
should contain only alphabets"); } }
</script> </head>
CONT..
<body bgcolor="#5555“ text="white“
onSubmit="return v()">
<form name="f">
<center>
<table border="0"><br><br><br><br><br><br>
<tr>
<td align="center"> username:</td>
<td align="center"><input type="text" value=""
name="un"/></td> </tr>
<tr>
<td align="center">password:</td>
<td align="center"><input type="password"
value="" name="pw"/></td></tr>
<tr>
<td align="center" colspan="2"><input
type="submit" value="Submit">
<input type="reset" value="reset"/></td></tr>
</table></center></form> </body> </html>
COOKIES IN JAVASCRIPT
Cookies are data, stored in small text files, on our
computer.
Cookies were invented to remember information
about the user.
JavaScript can create, read, and delete cookies with
the document.cookie property.
With JavaScript, a cookie can be created like:
document.cookie = "username=Ayantu";
We can also add an expiry date (in UTC time). By
default, the cookie is deleted when the browser is
closed. document.cookie = "username=Ayantu;
expires=Thu, 18 Dec 2019 12:00:00 UTC";
With JavaScript, we can read cookies like:
<script>
{
document.write(document.cookie);
}
</script>
CONT..
Deleting a cookie is very simple.
Just set the “expires” parameter to a passed
date.
document.cookie = "username=Ayantu;
expires=Thu, 01 Jan 1970 00:00:00 UTC;
path=/;" ;
Session: - A session uniquely identifies and
provides continuity for a user’s website
usage to a better degree than an IP address or
cookie could (essentially, by using both
together)
Session Cookie: - A cookie that is deleted
when the web browser is closed.
USING JAVASCRIPT ON HTML FORMS
JavaScript makes HTML pages more dynamic
and interactive.
JavaScript can be used to validate HTML
forms.
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.
JavaScript is used for client side form
validation.
If a form field (fieldname) is empty, this
function alerts a message, and returns false,
to prevent the form from being submitted:
function validateForm() {
var x = document.forms ["myForm"]
["fieldname"].value;
if (x == "") {
alert("Name must be filled out");
return false;
}}
The function can be called when the form is
submitted.
<form name="myForm"
action="/action_page.php" onsubmit="return
validateForm()" method="post">
Name: <input type="text" name="fname">
<input type="submit" value="Submit">
</form>
WHAT IS THE DOM?
The DOM is a W3C (World Wide Web
Consortium) standard.
The DOM defines a standard for accessing
documents:
"The W3C Document Object Model (DOM) is a
platform and language-neutral interface that
allows programs and scripts to dynamically
access and update the content, structure,
and style of a document.
WHAT IS THE HTML 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
In other words: The HTML DOM is a standard
for how to get, change, add, or delete HTML
elements.
1. JAVASCRIPT HTML DOM WINDOW OBJECT
The window object represents an open
window in a browser.
If a document contain frames (<iframe>
tags), the browser creates one window object
for the HTML document, and one additional
window object for each frame.
Note: There is no public standard that applies
to the Window object, but all major
browsers support it.
Window object properties and methods:
1. self :- it returns the current window
2. status:- it sets or returns the text in the
status bar of a window
3. top:- it returns the topmost browser window
2. JAVASCRIPT HTML DOM DOCUMENT:
The HTML DOM document object is the owner of
all other objects in our web page.
The document object represents our web page.
When we want to access any element in an
HTML page, we always start with accessing the
document object.
Below are some examples of how we can use
the document object to access and manipulate
HTML.
DOM Document methods for finding HTML
elements
document.getElementById(id):- Find an element by
element id.
document.getElementsByTagName(name):- Find
elements by tag name
document.getElementsByClassName(name):- Find
elements by class name
CONT..
DOM Document methods for changing HTML
elements
element.innerHTML = new html content:- Change the inner
HTML of an element
element.attribute = new value: - Change the attribute value
of an HTML element.
element.setAttribute(attribute, value):- Change the attribute
value of an HTML element
element.style.property = new style:- Change the style of an
HTML element
DOM Document methods for Adding and Deleting
Elements
document.createElement(element):- Create an HTML
element
document.removeChild(element):- Remove an HTML
element
document.appendChild(element):- Add an HTML element
document.replaceChild(element):- Replace an HTML
element
document.write(text):- Write into the HTML output stream
JAVASCRIPT HTML DOM ELEMENTS
Used to find and access HTML elements in an HTML page.
There are a couple of 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
The easiest way to find an HTML element in the DOM, is by
using the element id.
Example to find the element with id="intro":
var myElement = document.getElementById("intro");
example to find all <p> elements:
var x = document.getElementsByTagName("p");
To find all HTML elements with the same class name, use
getElementsByClassName().
This example returns a list of all elements with class="intro".
var x = document.getElementsByClassName("intro");
Finding elements by class name does not work in Internet
Explorer 8 and earlier versions.
FORM METHODS AND PROPERTIES
Document.forms:- returns an array of HTML
FormElement objects listing each of the
forms on the page.
We can then use any of the following
syntaxes to get an individual form:
document.forms[index]:- used to returns the
form at the specified index into the array of
forms.
document.forms[id]:- used to returns the form
whose ID is id.
document.forms[name]:- used to returns the
form whose name attribute's value is
name.
Q&A
I Thank You