Unit 3
Unit 3
Unit 3
Unit-3
Scripting languages, which can be embedded within HTML, commonly are used to add
functionality to a Web page, such as different menu styles or graphic displays or to serve
dynamic advertisements.
Introduction
JavaScript ( JS) is a dynamic language.
It is most commonly used as part of web browsers, whose implementations allow client-side
scripts to interact with the user, control the browser, communicate asynchronously, and alter
the document content that is displayed.
In addition, client-side scripts can control browser actions associated with a Web page.
Client-side scripts are almost written in the JavaScript language to control browser’s actions.
Client-side scripting can make Web pages more dynamic and more responsive
Introduction
HTML and CSS concentrate on a static rendering of a page; things do not change on the page
over time, or because of events.
To do these things, we use scripting languages, which allow content to change dynamically.
Not only this, but it is possible to interact with the user beyond what is possible with HTML.
Scripts are programs just like any other programming language; they can execute on the client
side or the server.
Tasks performed by client-side scripts
Checking correctness of user input
Monitoring user events and specifying reactions
Replacing and updating parts of a page
Changing the style and position of displayed elements dynamically
Modifying a page in response to events
Getting browser information
Making the Web page different depending on the browser and browser features
Generating HTML code for parts of the page
Pros & Cons of Client Side Scripting
Pros
Allow for more interactivity by immediately responding to users’ actions.
Execute quickly because they do not require a trip to the server.
The web browser uses its own resources, and eases the burden on the server.
It saves network bandwidth.
Cons
Code is loaded in the browser so it will be visible to the client.
Code is modifiable.
Local files and databases cannot be accessed.
User is able to disable client side scripting
Client V/S Server Side Scripting
Client V/S Server Side Scripting
What is difference between Java script and JAVA?
Java is a statically typed language; JavaScript is dynamic.
Java constructors are special functions that can only be called at object creation; JavaScript
"constructors" are just standard functions.
Java requires all non-block statements to end with a semicolon; JavaScript inserts semicolons at
the ends of certain lines.
Java has an implicit this scope for non-static methods, and implicit class scope; JavaScript has
implicit global scope
Embedded JavaScript
JavaScript can be embedded in an HTML document.
The script tag has effect of the stopping the JavaScript being printed out as well as indentifying
the code enclosed.
The JavaScript can be placed in the head section of your HTML or the body.
Embedded JavaScript
The Scripts placed in the body section are executed as the page loads and can be used to
generate the content of the page.
As well as the body section, JavaScript can also be placed in the head part.
The advantages of putting a script in there are that it loads before the main body.
Code
<html>
<head>
<title>HTML script Tag</title>
</head>
<body>
<script type="text/javascript">
document.write("<h1>This is a heading</h1>");
</script>
</body>
</html>
External JavaScript
If you want to use the same script on several pages it could be a good idea to place the code in a
separate file, rather than writing it on each.
That way if you want to update the code, or change it, you only need to do it once.
Simply take the code you want in a separate file out of your program and save it with the
extension .js.
Code
<html>
<head>
<title>HTML script</title>
</head>
<body>
<script src="myScript.js"></script>
</body>
</html>
External JavaScript
We can create external JavaScript file and embed it in many html pages.
It provides code reusability because single JavaScript file can be used in several html pages.
To embed the External JavaScript File to HTML we can use script tag with src attribute in the
head section to specify the path of JavaScript file.
For Example :
<script type="text/javascript" src="message.js"></script>
External JavaScript (Example)
message.js
function myAlert(msg) {
if(confirm("Are you sure you want to display the message????")) {
alert(msg);
}
else {
alert("Message not Displayed as User Cancled Operation");
}
}
myHtml.html
<html>
<head>
<script src=“message.js”></script>
</head>
<body>
<script> myAlert(“Hello World”); </script>
</body>
</html>
<script> tag
The <script> tag is used to define a client-side script (JavaScript).
The <script> element either contains scripting statements, or it points to an external script file
through the src attribute.
Example :
Code
Code
<html>
<html>
<head>
<head>
<title>HTML script Tag</title>
<title>HTML script Tag</title>
</head>
</head>
<body>
<body>
<script type="text/javascript">
<script src=“PathToJS”>
// Java Script Code Here
</script>
</script>
</body>
</body>
</html>
</html>
JavaScript Variables
Variables in JavaScript behave the same as variables in most popular programming languages
(C, C++, etc) do, but in JavaScript you don't have to declare variables before you use them.
A variable is a symbolic name that represents some data that you set.
When using a variable for the first time it is not necessary to use "var" before the variable name.
The value of the variable carname will still have the value "Volvo" after the execution of the
following two statements.
varcarname="Volvo";
varcarname;
JavaScript Operators
Operators in JavaScript are very similar to operators that appear in other programming
languages.
Most often these operations are arithmetic (addition, subtraction, etc), but not always.
Operator Name
+ Addition
- Subtraction
* Multiplication
/ Division
% Modulus
= Assignment
JavaScript Arrays
An array is a collection of data, each item in array has an index to access it.
Regular
varmyCars=new Array(); myCars[0]="Saab"; myCars[1]="Volvo"; myCars[2]="BMW";
Condensed
varmyCars=new Array("Saab","Volvo","BMW");
JavaScript Array
Literal
varmyCars=["Saab","Volvo","BMW"];
Access an Array
You refer to an element in an array by referring to the index number.
This statement access the value of the first element in myCars.
var name=myCars[0];
myCars[0]="Opel";
JavaScript Functions
A JavaScript function is a block of code designed to perform a particular task.
A JavaScript function is defined with the function keyword, followed by a name, followed by
parentheses ().
If the function was invoked from a statement, JavaScript will "return" to execute the code after
the invoking statement.
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
Automatically (self invoked)
JavaScript Function
<html>
<body>
<script type=”text/javascript”>
var z= multXbyY(10,15);
document.write(“The result is” +z);
functionmultXbyY(x,y) {
document.write(“x is ” +x);
document.write(“y is ”+y);
return x*y;
}
</script>
</body></html>
JavaScript Conditions
Conditional statements are used to perform different actions based on different conditions.
In JavaScript we have the following conditional statements:
if statement - use this statement to execute some code only if a specified condition is true
if...else statement - use this statement to execute some code if the condition is true and another
code if the condition is false
if...else if…else statement - use this statement to select one of many blocks of code to be
executed.
switch statement - use this statement to select one of many blocks of code to be executed
JavaScript Conditions
If...else Statement
Use the if....else statement to execute some code if a condition is true and another code if the condition is not true.
if (condition)
{
code to be executed if condition is true
}
else
{
code to be executed if condition is not true
}
JavaScript Conditions
If...else if...else Statement
Use the if....else if...else statement to select one of several blocks of code to be executed.
if (condition1)
{
code to be executed if condition1 is true
}
else if (condition2) {
code to be executed if condition2 is true
}
else {
code to be executed if neither condition1 nor condition2 is true
}
JavaScript Conditions
Switch Statement
Use the switch statement to select one of many blocks of code to be executed.
switch(n)
{
case 1:
execute code block 1 break;
case 2:
execute code block 2 break;
default:
code to be executed if n is different from case 1 and 2
}
The default Keyword
Use the default keyword to specify what to do if there is no match.
Conditions
If condition switch
switch(expression)
if(a>10)
{
{ case lbl1:
alert(“A is > that 10”); // code to execute
} break;
case lbl2:
// code to execute
break;
}
ternary operator
max = a>b ? a : b ;
Loops
for loop while loop do while loop
Use when you know how many Loops through block of code Execute block at least once
repetitions you want to do while condition is true then repeat while condition is
true
syntax
for(initialize ; condition ; syntax syntax
increment) { … } while(condition) { … } do{ … } while (condition);
example
for(x=0;x<10;x++) { example example
// Code Here while (x<10) { do{
} //Code Here // Code Here
} } while (x<10)
Strings
A string can be defined as a sequence of letters, digits, punctuation and so on.
Strings can be joined together with the + operator, which is called concatenation.
For Example,
mystring = “my college name is ” + “SVBIT”;
When an alert box pops up, the user will have to click "OK" to proceed.
Code
<script>
</script>
JavaScript Objects
An object is just a special kind of data, with properties and methods.
This example uses the length property of the Javascript’s inbuilt object(String) to find the
length of a string:
var message="Hello World!";
var x=message.length;
JavaScript Objects
Accessing Object Methods
Methods are the actions that can be performed on objects.
This example uses the toUpperCase method of the String object to convert string to upper
case:
Code
<script>
var x=Math.PI;
var y=Math.sqrt(16);
</script>c
Math Object (Cont.)
Math object has some properties which are,
Properties Description
PI Returns PI(approx.3.14)
This can then be used to start a new object that you can then give new properties and methods.
In object- oriented programming such a new object is usually given a constructor to initialize
values when it is first created.
User Defined Objects
However, it is also possible to assign values when it is made with literal values.
example
<script>
person={
firstname: “Mayur",
lastname: “Prajapati",
age: 50,
eyecolor: "blue"
}
alert(person.firstname person.lastname + " is " + person.age + " years old.");
</script>
Document Object Model (DOM)
The Document Object Model is a platform and language neutral interface that will allow programs
and scripts to dynamically access and update the content, structure and style of documents.
The window object is the primary point from which most other objects come.
From the current window object access and control can be given to most aspects of the browser
features and the HTML document.
When we write :
document.write(“Hello World”);
We are actually writing :
window.document.write(“Hello World”);
The window is just there by default
DOM (Cont)
This window object represents the window or frame that displays the document and is the global
object in client side programming for JavaScript.
All the client side objects are connected to the window object.
window
JavaScript
<script>
function myFunction()
{
var txt = document.getElementById(“myText”);
alert(txt.value);
}
</script>
getElementsByTagName()
When we suppose to get the reference of the elements from HTML in JavaScript using name of
the tag specified in the HTML we can use this method.
It will return the array of elements with the provided tag name.
Example :
JavaScript
HTML
<script>
<html>
function myFunction() {
<body>
a=document.getElementsByTagName(“input”);
<input type=“text” name=“uname”>
alert(a[0].value);
<input type=“text” name=“pword”>
alert(a[1].value);
</body>
}
</html>
</script>
Forms using DOM
We can access the elements of form in DOM quite easily using the name/id of the form.
Example :
HTML JS
<html> function f()
<body> {
<form name=“myForm”> var a = document.forms[“myForm”];
<input type=“text” name=“uname”> var u = a.uname.value;
<input type=“text” name=“pword”> var p = a.pword.value;
<input type=“button” onClick=“f()”> if(u==“admin” && p==“123”)
</form> {
</body> alert(“valid”);
</html> }
else
{
alert(“Invalid”);
}
}
Validation
Validation is the process of checking data against a standard or requirement.
Form validation normally used to occur at the server, after client entered 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.
This was really a lengthy process which used to put a lot of burden on the server.
JavaScript provides a way to validate form's data on the client's computer before sending it to
the web server.
Validation (Cont.)
Form validation generally performs two functions.
1. Basic Validation
Emptiness
Confirm Password
Length Validation etc……
var pattern = "^ [ w]$"; // will allow only words in the string
var regex = new RegExp(pattern);
If(regex.test(testString)){
//Valid
} else {
//Invalid
}
RegExp (Cont.) (Metacharacters)
To find word characters in the string we can use w
We can also use [a-z], [A-Z] or [a-zA-Z] for the same
The main problem with DHTML, which was introduced in the 4.0 series of browsers, is
compatibility.
The main focus generally when speaking of DHTML is animation and other such dynamic effects.
DHTML (Cont)
We can obtain reference of any HTML or CSS element in JavaSCript using below 3 methods.
1. document.getElementById(“IdOfElement”)
2. document.getElementsByName(“NameOfElement”)
3. document.getElementsByTagName(“TagName”)
After obtaining the reference of the element you can change the attributes of the same using
reference.attribute syntax.
JavaScript functions are executed in the sequence they are called. Not in the sequence they are
defined.
This example will end up displaying "Goodbye":
Callbacks in Javascript
Function Sequence:
JavaScript functions are executed in the sequence they are called. Not in the sequence they are
defined.
This example 1 will end up displaying "Goodbye“ and example 2 will end up displaying "Hello":
Callbacks in Javascript
Sequence Control
Sometimes you would like to have better control over when to execute a function.
Suppose you want to do a calculation, and then display the result.
You could call a calculator function (myCalculator), save the result, and then call another
function (myDisplayer) to display the result:
Callbacks in Javascript
Sequence Control
Or, you could call a calculator function (myCalculator), and let the calculator function call the
display function (myDisplayer):
Callbacks in Javascript
The problem with the first example above, is that you have to call two functions to display the
result.
The problem with the second example, is that you cannot prevent the calculator function from
displaying the result.
Earlier in this tutorial, you learned that functions can have parameters:
The argument object contains an array of the arguments used when the function was called
(invoked).
This way you can simply use a function to find (for instance) the highest value in a list of
numbers:
Function as arguments in Javascript
Function as arguments in Javascript
JSON
JSON or JavaScript Object Notation is a lightweight text-based open standard designed for
human-readable data interchange. Conventions used by JSON are known to programmers, which
include C, C++, Java, Python, Perl, etc.
JSON format is used for serializing and transmitting structured data over network connection.
Web services and APIs use JSON format to provide public data.
Curly braces hold objects and each name is followed by ':'(colon), the name/value pairs are
separated by , (comma).
1 Number
double- precision floating-point format in JavaScript
2 String
double-quoted Unicode with backslash escaping
3 Boolean
true or false
4 Array
an ordered sequence of values
5 Value
it can be a string, a number, true or false, null etc
6 Object
an unordered collection of key:value pairs
7 Whitespace
can be used between any pair of tokens
8 null
empty
Simple Example in JSON
The following example shows how to use JSON to store information related to books based on their
topic and edition.
Simple Example in JSON
Index.html
Simple Example in JSON
Index.html