tag, strings, arrays, and linking to external JavaScript files. The document is intended to teach the basics of JavaScript for controlling browser actions and making web pages more dynamic."> tag, strings, arrays, and linking to external JavaScript files. The document is intended to teach the basics of JavaScript for controlling browser actions and making web pages more dynamic.">
WT PPT Javascript
WT PPT Javascript
Web Technology
Web Development
Unit-6
Unit
XML – 3
Java Script
(JS)
Outline
1. Introduction
I. Task Performed by Client side Scripts
II. Pros & Cons of Client side Scripts
III. Client side Scripts V/S Server side Scripts
2. Variables
3. Functions
4. Conditions & Loops
5. Pop up boxes
6. External JavaScript
7. JavaScript Objects
8. DOM
9. DHTML
Unit – 5: JS 2
Introduction
. For a Web page, HTML supplies document content and structure
while CSS provides presentation styling
. 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
Unit – 5: JS 3
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
Unit – 5: JS 4
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
Unit – 5: JS 5
Client V/S Server Side Scripting
Server Side Scripting Client Side Scripting
Unit – 5: JS 6
Client V/S Server Side Scripting (Cont)
Server Side Scripting Client Side Scripting
Unit – 5: JS 7
<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>
Unit – 5: JS 8
Variables
. A variable can contain several types of value:
• Number : a numeric value e.g. 156, 100, 1.2
• String : character wrapped in quotes e.g. “India”
• Boolean : a value of true or false
• Null : an empty variable
• Function : a function name
• Object : an object
. Attributes of Javascript variables :
• It is a case sensitive. (mynum and MyNum are different variables)
• It cannot contain punctuation, space or start with a digit
• It cannot be a JavaScript reserved word
Unit – 5: JS 9
Conditions
If condition switch
if(a>10) switch(expression)
{ {
alert(“A is > then 10”); case lbl1:
} // code to execute
break;
ternary operator case lbl2:
max = a>b ? a : b ; // code to execute
break;
}
Unit – 5: JS 10
Loops
for loop while loop do while loop
Use when you know how Loops through block of code Execute block at least once
many repetitions you want while condition is true then repeat while condition
to do is true
Unit – 5: JS 11
Strings
. A string can be defined as a sequence of letters, digits,
punctuation and so on.
. A string in a JavaScript is wrapped with single or double quotes
. Strings can be joined together with the + operator, which is called
concatenation.
For Example,
mystring = “my college name is ” + “SCE”;
. As string is an object type it also has some useful features.
For Example,
lenStr = mystring.length;
Which returns the length of the string in integer
Unit – 5: JS 12
Strings (Cont.)
. There are also number of methods available for string.
Method Description
Unit – 5: JS 13
Strings (Cont.)
. An escape sequence is a sequence of characters that does not
represent itself when used inside a character or string, but is
translated into another character or a sequence of characters
that may be difficult or impossible to represent directly.
. Some Useful Escape sequences :
Sequence Character
Unit – 5: JS 14
Arrays
. An array is a collection of data, each item in array has an index to
access it.
. Ways to use array in JavaScript
• var myArray = new Array();
myArray[0] = “SAL”;
myArray[1] = 222;
myArray[2] = false;
• var myArray = new Array(“SAL” , 123 , true);
Unit – 5: JS 15
Functions
. A JavaScript function is a block of code designed to perform a
particular task.
. A JavaScript function is executed when "something" invokes it.
. A JavaScript function is defined with the function keyword,
followed by a name, followed by parentheses ().
. The parentheses may include parameter names separated by
commas: (parameter1, parameter2, ...)
. The code to be executed, by the function, is placed inside curly
brackets.
Code
. Example : function myFunction(p1, p2) {
return p1 * p2;
}
Unit – 5: JS 16
Functions (Cont.)
. When JavaScript reaches a return statement, the function will
stop executing.
. 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)
Unit – 5: JS 17
Pop up Boxes
. Popup boxes can be used to raise an alert, or to get confirmation
on any input or to have a kind of input from the users.
. JavaScript supports three types of popup boxes.
• Alert box
• Confirm box
• Prompt box
Unit – 5: JS 18
Alert Box
. An alert box is used if you want to make sure information comes
through to the user.
. When an alert box pops up, the user will have to click "OK" to
proceed.
. It can be used to display the result of validation.
Code
<html>
<head>
<title>Alert Box</title>
</head>
<body>
<script>
alert("Hello World");
</script>
</body>
</html>
Unit – 5: JS 19
Confirm Box
. A confirm box is used if you want the user to 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.
. Example :
Code
<script>
var a = confirm(“Are you sure??");
if(a==true) {
alert(“User Accepted”);
}
else {
alert(“User Cancled”);
}
</script>
Unit – 5: JS 20
Prompt Box
. A prompt box is used if you want the user to input a value.
. When a prompt box pops up, user have to click either "OK" or
"Cancel" to proceed, If the user clicks "OK" the box returns the
input value, If the user clicks "Cancel" the box returns null.
Code
<script>
var a = prompt(“Enter Name");
alert(“User Entered ” + a);
</script>
Unit – 5: JS 21
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.
. An external JavaScript file must be saved by .js extension.
. 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>
Unit – 5: JS 22
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>
Unit – 5: JS 23
JavaScript Objects
. An object is just a special kind of data, with properties and
methods.
. Accessing Object Properties
• Properties are the values associated with an object.
• The syntax for accessing the property of an object is below
objectName.propertyName
• 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;
Unit – 5: JS 24
JavaScript Objects (Cont.)
. Accessing Object Methods
• Methods are the actions that can be performed on objects.
• You can call a method with the following syntax.
objectName.methodName()
• This example uses the toUpperCase method of the String object to convert
string to upper case:
var message="Hello World!";
var x=message.toUpperCase();
Unit – 5: JS 25
JavaScript’s inbuilt Objects
. JavaScript comes with some inbuilt objects which are,
• String
• Date
• Array
• Boolean
• Math
• RegExp
etc….
Unit – 5: JS 26
Math Object in JavaScript
. The Math object allows you to perform mathematical tasks.
. The Math object includes several mathematical constants and
methods.
. Example for using properties/methods of Math:
Code
<script>
var x=Math.PI;
var y=Math.sqrt(16);
</script>
Unit – 5: JS 27
Math Object (Cont.)
. Math object has some properties which are,
Properties Description
E Returns Euler's number(approx.2.718)
LN2 Returns the natural logarithm of 2 (approx.0.693)
LN10 Returns the natural logarithm of 10 (approx.2.302)
LOG2E Returns the base‐2 logarithm of E (approx.1.442)
LOG10E Returns the base‐10 logarithm of E (approx.0.434)
PI Returns PI(approx.3.14)
SQRT1_2 Returns square root of ½
SQRT2 Returns square root of 2
Unit – 5: JS 28
Math Methods (Cont.)
Method Description Method Description
abs(x) Returns the absolute value of x exp(x) Returns the value of Ex
sin(x) Returns the sine of x (x is in ceil(x) Returns x, rounded upwards
radians) to the nearest integer
cos(x) Returns the cosine of x (x is in floor(x) Returns x, rounded
radians) downwards to the nearest
tan(x) Returns the tan of x (x is in integer
radians) log(x) Returns the natural
acos(x) Returns the arccosine of x, in logarithm(base E) of x
radians round(x) Rounds x to the nearest
asin(x) Returns the arcsine of x, in radians integer
Unit – 5: JS 29
User Defined Objects
. JavaScript allows you to create your own objects.
. The first step is to use the new operator.
var myObj= new Object();
. This creates an empty object.
. 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.
Unit – 5: JS 30
User - Defined Objects (Cont.)
. However, it is also possible to assign values when it is made with
literal values.
example
<script>
person={
firstname: "SCE",
lastname: "College",
age: 50,
eyecolor: "blue"
}
alert(person.firstname + " is " + person.age + " years old.");
</script>
Unit – 5: JS 31
User - Defined Objects (Cont.)
. A constructor is pre defined method that will initialize your object.
. To do this in JavaScript a function is used that is invoked through
the new operator.
. Any properties inside the newly created object are assigned using
this keyword, referring to the current object being created.
example
<script>
function person(firstname, lastname, age){
this.firstname = firstname;
this.lastname = lastname;
this. changeFirstName = function (name){ this.firstname = name };
}
var person1=new person("Narendra","Modi",50);
person1.changeFirstName(“NAMO”);
alert(person1.firstname + “ ”+ person1.lastname);
</script>
Unit – 5: JS 32
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
Unit – 5: JS 33
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
Unit – 5: JS 34
Document Object Properties
Property Description
domain document
Unit – 5: JS 35
Document Object Methods
Method Description
Unit – 5: JS 36
getElementById()
. When we suppose to get the reference of the element from HTML
in JavaScript using id specified in the HTML we can use this
method.
HTML
. Example : <html>
<body>
<input type=“text” id=“myText”>
</body>
</html>
JavaScript
<script>
function myFunction()
{
var txt = document.getElementById(“myText ”);
alert(txt.value);
}
</script>
Unit – 5: JS 37
getElementsByName()
. When we suppose to get the reference of the elements from
HTML in JavaScript using name specified in the HTML we can use
this method.
. It will return the array of elements with the provided name.
. Example :
Unit – 5: JS 38
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 :
HTML JavaScript
<html> <script>
<body> function myFunction() {
<input type=“text” name=“uname”> a=document.getElementsByTagName(“input”);
<input type=“text” name=“pword”> alert(a[0].value);
</body> alert(a[1].value);
</html> }
</script>
Unit – 5: JS 39
Forms using DOM
. We can access the elements of form in DOM quite easily using the
name/id of the form.
. Example : JS
function f()
HTML {
<html> var a = document.forms[“myForm”];
<body> var u = a.uname.value;
<form name=“myForm”> var p = a.pword.value;
<input type=“text” name=“uname”> if(u==“admin” && p==“123”)
<input type=“text” name=“pword”> {
<input type=“button” onClick=“f()”> alert(“valid”);
</form> }
</body> else
</html> {
alert(“Invalid”);
}
}
Unit – 5: JS 40
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.
Unit – 5: JS 41
Validation (Cont.)
Form validation generally performs two functions.
1. Basic Validation
• Emptiness
• Confirm Password
• Length Validation etc……
2. Data Format Validation
Secondly, the data that is entered must be checked for
correct form and value.
• Email Validation
• Mobile Number Validation
• Enrollment Number Validation etc….
Unit – 5: JS 42
Validation using RegExp
. A regular expression is an object that describes a pattern of
characters.
. Regular expressions are used to perform pattern‐matching and
"search‐and‐replace" functions on text.
. example:
var pattern = "^ [\\w]$"; // will allow only words in the string
var regex = new RegExp(pattern);
If(regex.test(testString)){
//Valid
} else {
//Invalid
}
Unit – 5: JS 43
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
. To find non-word characters in the string we can use \W
. to find digit characters in the string we can use \d
• We can also use [0‐9] for the same
. To find non-digit characters in the string we can use \D
. We can use \n for new line and \t for tab
Unit – 5: JS 44
RegExp (Cont.) (Quantifiers)
Quantifier Description
n+ Matches any string that contains at least one n
n* Matches any string that contains zero or more occurrences of n
n? Matches any string that contains zero or one occurrences of n
n$ Matches any string with n at the end of it
^n Matches any string with n at the beginning of it
n{X} Matches any string that contains a sequence of X n's
n{X,Y} Matches any string that contains a sequence of X to Y n's
n{X,} Matches any string that contains a sequence of at least X n's
Unit – 5: JS 45
Email Validation Using RegExp
JavaScript
<script>
function checkMail()
{
var a = document.getElementById("myText").value;
var pattern ="^[\\w‐_\.]*[\\w‐_\.]\@[\\w]\.+[\\w]+[\\w]$”;
var regex = new RegExp(pattern);
if(regex.test(a))
{
alert("Valid");
}
else
{
alert("Invalid");
}
}
</script>
Unit – 5: JS 46
DHTML – Combining HTML,CSS & JS
. DHTML, or Dynamic HTML, is really just a combination of HTML,
JavaScript and CSS.
. 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.
Unit – 5: JS 47
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
. For Example :
HTML Code JS Code
Unit – 5: JS 48
DHTML (Cont) (Example)
JavaScript
<html>
<body>
<div id=“myDiv”>
Red Alert !!!!!!
</div>
<script>
var objDiv = document.getElementById(“myDiv”);
var colors = [‘white’,’yellow ’,’orange’,’red’];
var nextColor = 0;
setInterval(“objDiv.style.backgroundColor = colors[nextColor++%colors.length];”,500);
</script>
</body>
</html>
Unit – 5: JS 49
HTML Element Properties
Event Description
Unit – 5: JS 50
Mouse Events
Event Attribute Description
Unit – 5: JS 51
Keyboard Events
Event Attribute Description
Unit – 5: JS 52
Frame/Object Events
Event Attribute Description
Unit – 5: JS 53
Form Events
Event Attribute Description
Unit – 5: JS 54