WDUnit 4
WDUnit 4
Unit-4
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
Introduction
Javascript is a high level dynamic interpreted programming language. It
allows client-side scripting to create completely dynamic web
applications and web sites.
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
Javascript work for front end and back end of web pages.
Java script run on browser.
Script can be executed in the browser itself.
Javascript and java are different programming language.
It can be executed on the browser as well as server.
Javascript is safe language when used in browser.
There are languages that get transpiled to javascript.
Ex- coffeeScript,typescript
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
Server Side Scripting Client Side Scripting
Server side scripting is used to create Client side scripting is used when the users
dynamic pages based on a number of browser already has all the code and the
conditions when the users browser makes a page is altered on the basis of the users
request to the server. input.
The Web Server executes the server side The Web Browser executes the client side
scripting that produces the page to be sent scripting that resides at the user’s computer.
to the browser.
Server side scripting is used to connect to Client side scripting cannot be used to
the databases and files that reside on the connect to the databases and files on the
web server. web server.
Client V/S Server Side Scripting (Cont)
Server Side Scripting Client Side Scripting
Server resources can be accessed by the Browser resources can be accessed by the
server side scripting. client side scripting.
Server side scripting can’t be blocked by the Client side scripting is possible to be blocked
user. by the user.
Examples of Server side scripting languages : Examples of Client side scripting languages :
PHP, JSP, ASP, ASP.Net, Ruby, Perl and many Javascript, VB script, etc.
more.
Setup JavaScript Development Environment
we need a webserver to run a web application, but we will use a single HTML
web page to run our JavaScript code.
Browser
• Microsoft Edge
• Google Chrome
• Mozilla FireFox
• Safari
• Opera
IDEs for JavaScript Application Development
• you can install any open-sourced or licensed IDE (Integrated Development
Environment) to get the advantage of IntelliSense support for JavaScript
and syntax error/warning highlighter for rapid development.
•
Visual Studio Code (Free, cross-platform)
• Eclipse (Free, cross-platform)
• Atom (Free, cross-platform)
• Notepad++ (Free, Windows)
• Code Lobster (Free, cross-platform)
• WebStorm (Paid, cross-platform)
Online Editors for JavaScript
• jsfiddle.net
• jsbin.com
• playcode.io
<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>
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. “rajkot”
• 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
Keywords
Conditions
If condition switch
if(a>10) switch(expression)
{ {
alert(“A is > that 10”); case lbl1:
} // code to execute
break;
ternary operator case lbl2:
max = a>b ? a : b ; // code to execute
break;
}
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
myHtml.html
<html>
<head>
<script src=“message.js”></script>
</head>
<body>
<script> myAlert(“Hello World”); </script>
</body>
</html>
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;
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();
JavaScript’s inbuilt Objects
JavaScript comes with some inbuilt objects which are,
• String
• Date
• Array
• Boolean
• Math
• RegExp
etc….
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>
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
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
window
JavaScript
<script>
function myFunction()
{
var txt = document.getElementById(“myText”);
alert(txt.value);
}
</script>
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 :
HTML JavaScript
<html> <script>
<body> function myFunction()
<input type=“text” {
name=“myText”> a=document.getElementsByName(“myText”)[0];
</body> alert(a.value);
</html> }
</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 :
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>
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”);
}
}
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……
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….
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
}
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
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
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>
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.
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