Unit-4 Web Technology
Unit-4 Web Technology
Unit-4 JavaScript
What is client-side scripting language?
In simple words, client side scripting is a process in which scripts are executed by browsers
without connecting the server.
The code executes on the browser of client’s computer either during the loading of web page or
after the web page has been loaded. Client side scripting is mainly used for dynamic user
interface elements, such as pull-down menus, navigation tools, animation buttons, data
validation purpose, etc. The browser (temporarily) downloads the code in the local computer
and starts processing it without the server. Therefore, the client side scripting is browser
dependent. JavaScript and jQuery are by far the most important client-side scripting languages
or web scripting languages and widely used to create a dynamic and responsive webpage and
websites.
What is JavaScript?
Ans: JavaScript is a text-based programming language that allows us to make web pages
interactive. Where HTML and CSS are languages that give structure and style to web pages,
JavaScript improves the user experience of the web page by converting it from a static page
into an interactive one.
Advantages of JavaScript
• Less server interaction − You can validate user input before sending the page off to the
server. This saves server traffic, which means less load on your server.
• Immediate feedback to the visitors − They don't have to wait for a page reload to see if
they have forgotten to enter something.
• Increased interactivity − You can create interfaces that react when the user hovers
over them with a mouse or activates them via the keyboard.
• Richer interfaces − You can use JavaScript to include such items as drag-and-drop
components and sliders to give a Rich Interface to your site visitors.
Difference between JavaScript and HTML
HTML JAVASCRIPT
HTML is the most basic building block of the JavaScript is a high-level scripting language
Web. It defines the meaning and structure of introduced by Netscape to be run on the
web content. client-side of the web browser.
HTML pages are static which means the It manipulates content to create dynamic
content cannot be changed. web pages
Jhalnath | GM COLLEGE
Page |2
Lexical Structure
The lexical structure of a programming language is the set of elementary rules that specifies
how you write programs in that language. It is the lowest-level syntax of a language:
Unicode
JavaScript is written in Unicode. This means we can use Emojis as variable names, but more
importantly, you can write identifiers in any language, for example Japanese or Chinese, with
some rules.
Semicolons
Semicolons aren’t mandatory, and JavaScript does not have any problem in code that does not
use them, and lately many developers.
White space
JavaScript does not consider white space meaningful. Spaces and line breaks can be added in
any fashion you might like.
Case sensitive
JavaScript is case sensitive. A variable named something is different from Something. The same
goes for any identifier.
Comments
You can use two kind of comments in JavaScript:
/* */
//
The first can span over multiple lines and needs to be closed and the second comments
everything that’s on its right, on the current line.
Literals and Identifiers
We define literal as a value that is written in the source code, for example a number, a string, a
boolean or also more advanced constructs, like Object Literals or Array Literals.
Jhalnath | GM COLLEGE
Page |3
Keywords
We can’t use as identifiers any of the following words:
break, do, instanceof, typeof, case, else, new, var, catch, finally, return, void, continue, for,
switch, while, debugger, function, this, with, default, if, throw, delete, in, try, class, enum,
extends, super, const, export, import, implements, let, private, public, interface, package,
protected, static, yield
JavaScript Variables
A variable is simply a name of storage location which stores the data value that can be changed
later on.
The general rules for constructing names for variables are:
• Names can contain letters, digits, underscores, and dollar signs.
• Names must begin with a letter
• Names are case sensitive (y and Y are different variables)
• Reserved words cannot be used as variable names
Let var
let is block-scoped. var is function scoped.
let does not allow to redeclare variables. var allows to redeclare variables.
Jhalnath | GM COLLEGE
Page |4
• Using var
The variable declared inside a function with var can be used anywhere within a function. For
example,
// program to print text
// variable a cannot be used here
function greet() {
// variable a can be used here
var a = 'hello';
console.log(a);
}
// variable a cannot be used here
greet(); // hello
Example:
var x=2;
var y=6;
var z=x+y;
• Using let
• Variables defined with let cannot be Redeclared.
Example
let x = "Hello World";
let x = 0;
// SyntaxError: 'x' has already been declared
Example
{
let x = 2;
}
// x can NOT be used here
• Using const
• Variables defined with const cannot be Redeclared.
Example
const x = 5;
const x = 0;
// SyntaxError: 'x' has already been declared
Jhalnath | GM COLLEGE
Page |5
Example
const PI = 3.14159;
PI = 3.14; // This will give an error
• JavaScript const variables must be assigned a value when they are declared:
Example
const g = 9.8; //correct
const g;
g = 9.8; //incorrect
JavaScript evaluates expressions from left to right. Different sequences can produce
different results:
let x = 5+3+”Ram”;
output: 8Ram
let x = "Ram" + 5 + 3;
output: Ram53
Javascript Expression
An expression is a combination of values, variables, and operators.
Example;
x=5+2;
Here, 5+2 is an expression.
Statements
The programming instructions written in a program in a programming language are
known as statements.
Multiple statements on one line are allowed if they are separated with a semicolon.
a=2;b=3;z=a+b;
Dialog Boxes in Javascript
Dialog boxes are use to provide essential information to the user through pop-up
window.
There are mainly 3 types of dialog box in javascript.
Jhalnath | GM COLLEGE
Page |6
i. alert
ii. confirm
iii. prompt
i. Alert Box
An alert box is often used to “alert” the user for some information message. It
contains a single statement and an OK button. When an alert box pops up, the user
needs to click the OK button to proceed.
Operator in Javascript
Operator is a symbols that can be used to perform mathematical, relational, bitwise,
conditional, or logical manipulations
a. Arithmetic Operator
Operator Use
+ Addition
- Subtraction
* Multiplication
/ Division
% Modulus
++ Increment
-- Decrement
Jhalnath | GM COLLEGE
Page |7
b. Assignment Operator
There are various Assignment Operators in JavaScript
c. Logical Operators
Operator Use
Jhalnath | GM COLLEGE
Page |8
d. Comparison Operators
Operator Use
== Is equal to
=== Exactly equal to – in value and type
!= Is not equal to
> Is greater than
< Is less than
>= Is greater than or equal to
<= Is less than or equal
to
e. String Operators
Operator Use
+ Concatenation
Function in JavaScript
A JavaScript function is a block of code designed to perform a particular task. A
JavaScript function is executed when "something" invokes it (calls it).
JavaScript Function Syntax
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, ...)
Jhalnath | GM COLLEGE
Page |9
Local Variables
Variables declared within a JavaScript function, become LOCAL to the function.
Jhalnath | GM COLLEGE
P a g e | 10
• If statement
We can use If statement if we want to check only a specific condition.
Syntax:
if (condition)
{
//lines of code to be executed if condition is true
}
<html>
<head>
<title>IF Statments!!!</title>
<script type="text/javascript">
var age = prompt("Please enter your age");
if(age>=18)
document.write("You are an adult <br />");
if(age<18)
document.write("You are NOT an adult <br />");
</script>
</head>
<body>
</body>
</html>
• If…Else statement
we use If….Else statement when there is a need to test two conditions and execute a
different set of codes.
Syntax:
if (condition)
{
Jhalnath | GM COLLEGE
P a g e | 11
Jhalnath | GM COLLEGE
P a g e | 12
{
//lines of code to be executed if condition1 is false and condition2 is false
}
<html>
<head>
<script type="text/javascript">
var one = prompt("Enter the first number");
var two = prompt("Enter the second number");
one = parseInt(one);
two = parseInt(two);
if (one == two)
document.write(one + " is equal to " + two + ".");
else if (one<two)
document.write(one + " is less than " + two + ".");
else
document.write(one + " is greater than " + two + ".");
</script>
</head>
<body>
</body>
</html>
\
JavaScript Arrays
In JavaScript, array is a single variable that is used to store different elements. It is often used
when we want to store list of elements and access them by a single variable.
Array Declaration
var Person = [ ]; // method 1
var Person = new Array(); // method 2
Initialization of an Array
Jhalnath | GM COLLEGE
P a g e | 13
or
var nums=new Array(3); //Creates an array of 3 undefined elements
nums[0]=10;
nums[1]=20;
nums[2]=30;
Example of Array:
<script>
var person=new Array("Ram","Hari","Gopal");
for (i=0;i<person.length;i++){
document.write(person[i] + "<br>");
}
</script>
a)For Loop
For loops are commonly used to count a certain number of iterations to repeat a statement.
Syntax
for ([initialization]; [condition]; [final-expression]) {
// statement
}
Example
<script>
var n1 = prompt("Please enter the number for multiplication table :", "0");
document.write("<h2> Multiplication for your need </h2>");
for( var n2=0;n2<=10;n2++)
{
document.write(n1+" x "+n2+" = "+n1*n2+"<br>");
}
</script>
Jhalnath | GM COLLEGE
P a g e | 14
Regular Expression
In JavaScript, a Regular Expression (RegEx) is an object that describes a sequence of
characters used for defining a search pattern. For example,
/^a...s$/
The above code defines a RegEx pattern. The pattern is: any five letter string starting with a
and ending with s. ( ex: match for alias)
MetaCharacters
Metacharacters are characters that are interpreted in a special way by a RegEx engine.
Here's a list of metacharacters:
[] . ^ $ * + ? {} () \ |
[] - Square brackets
We can complement (invert) the character set by using caret ^ symbol at the start of a
square-bracket.
. - Period
A period matches any single character (except newline '\n').
Expression String Matched?
a No match
.. ac 1 match
acd 1 match
Jhalnath | GM COLLEGE
P a g e | 15
^ - Caret
The caret symbol ^ is used to check if a string starts with a certain character.
a 1 match
^a abc 1 match
bac No match
abc 1 match
^ab
acb No match (starts with a but not followed by b)
$ - Dollar
The dollar symbol $ is used to check if a string ends with a certain character.
a 1 match
a$ formula 1 match
cab No match
* - Star
The star symbol * matches zero or more occurrences of the pattern left to it.
ma*n mn 1 match
Jhalnath | GM COLLEGE
P a g e | 16
man 1 match
mann 1 match
woman 1 match
+ - Plus
The plus symbol + matches one or more occurrences of the pattern left to it.
man 1 match
woman 1 match
? - Question Mark
The question mark symbol ? matches zero or one occurrence of the pattern left to it.
mn 1 match
man 1 match
ma?n
Jhalnath | GM COLLEGE
P a g e | 17
woman 1 match
{} - Braces
Consider this code: {n,m}. This means at least n, and at most m repetitions of the pattern left
to it.
Expression String Matched?
Let's try one more example. This RegEx [0-9]{2, 4} matches at least 2 digits but not more
than 4 digits.
Expression String Matched?
1 match (match at
ab123csde
ab123csde)
[0-9]{2,4}
12 and 345673 3 matches (12, 3456, 73)
1 and 2 No match
| - Alternation
Jhalnath | GM COLLEGE
P a g e | 18
Parentheses () is used to group sub-patterns. For example, (a|b|c)xz match any string that
matches either a or b or c followed by xz
Expression String Matched?
ab xz No match
\ - Backslash
Backslash \ is used to escape various characters including all metacharacters. For example,
\$a match if a string contains $ followed by a. Here, $ is not interpreted by a RegEx engine
in a special way.
If you are unsure if a character has special meaning or not, you can put \ in front of it. This
makes sure the character is not treated in a special way.
Jhalnath | GM COLLEGE
P a g e | 19
Regular expressions are used with the RegExp methods test() and exec() and with
the String methods match(), replace(), search(), and split().
Method Description
exec() Executes a search for a match in a string. It returns an array of information or null on a mismatch.
match() Returns an array containing all of the matches, including capturing groups, or null if no match is fou
matchAll() Returns an iterator containing all of the matches, including capturing groups.
search() Tests for a match in a string. It returns the index of the match, or -1 if the search fails.
Executes a search for a match in a string, and replaces the matched substring with a replacement
replace()
substring.
Executes a search for all matches in a string, and replaces the matched substrings with a replaceme
replaceAll()
substring.
split() Uses a regular expression or a fixed string to break a string into an array of substrings.
g Modifier
The "g" modifier specifies a global match. A global match finds all matches (compared to only
the first).
Jhalnath | GM COLLEGE
P a g e | 20
i Modifier
m Modifier
The "m" modifier specifies a multiline match. It only affects the behavior of start ^ and end $. ^
specifies a match at the start of a string. $ specifies a match at the end of a string. With the "m"
set, ^ and $ also match at the beginning and end of each line.
all there
is’
Garbage collection
Jhalnath | GM COLLEGE
P a g e | 21
Javascript objects
In JavaScript, an object is a standalone entity, with properties and type. Compare it with a cup,
for example. A cup is an object, with properties. A cup has a color, a design, weight, a material
it is made of, etc. The same way, JavaScript objects can have properties, which define their
characteristics.
Object Properties
Properties are the values associated with a JavaScript object. A JavaScript object is a collection
of unordered properties. Properties can usually be changed, added, and deleted, but some are
read only.
Object Constructors
A constructor is a special function that creates and initializes an object instance of a class. In
JavaScript, a constructor gets called when an object is created using the new keyword. The
purpose of a constructor is to create a new object and set values for any existing object
properties.
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Object Constructors</h2>
<p id="demo"></p>
<script>
// Constructor function for Person objects
function Person(first, last, age, eye) {
this.firstName = first;
this.lastName = last;
this.age = age;
this.eyeColor = eye;
}
// Create a Person object
const p1 = new Person("Ram", "Rai", 50, "blue");
// Display age
document.getElementById("demo").innerHTML =
"First person is " + p1.age + "years old.";
</script>
</body>
</html>
Jhalnath | GM COLLEGE
P a g e | 22
Prototype is used to provide additional property to all the objects created from a constructor
function. we cannot directly add a new property to an existing object constructor, a prototype
can be used to add properties and methods to a constructor function. And objects inherit
properties and methods from a prototype. For example,
The JavaScript prototype property allows you to add new properties to object constructors:
<html>
<body>
<h2>JavaScript Objects</h2>
<p>The prototype property allows you to add new methods to objects constructors:</p>
<p id="demo"></p>
<script>
function Person(first, last, age, eye) {
this.firstName = first;
this.lastName = last;
this.age = age;
this.eyeColor = eye;
}
//Person.nationality="English"; we cannot do this
Person.prototype.nationality = "English";//we have to do this
const myFather = new Person("John", "Doe", 50, "blue");
document.getElementById("demo").innerHTML =
"The nationality of my father is " + myFather.nationality;
</script>
</body>
</html>
JavaScript has several built-in or core language objects. These built-in objects are available
regardless of window content and operate independently of whatever page your browser has
loaded.
Jhalnath | GM COLLEGE
P a g e | 23
Array Object
Multiple values are stored in a single variable using the Array object.
To create empty array when don’t know the exact number of elements to be inserted in an
array
var arrayname =[ ];
Jhalnath | GM COLLEGE
P a g e | 24
unshift(), join(), indexOf(), lastIndexOf(), slice(startindex, endindex) are some of the methods
used in Array object.
Date Object
At times when user need to access the current date and time and also past and future date and
times. JavaScript provides support for working with dates and time through the Date object.
Dates may be constructed from a year, month, day of the month, hour, minute, and second,
and those six components, as well as the day of the week, may be extracted from a date.
getDate() - Returns the day of the month for the specified date
getDay() - Returns the day of the week for the specified date
Jhalnath | GM COLLEGE
P a g e | 25
getHours() - Returns the hour in the specified date according to local time.
getMilliseconds() - Returns the milliseconds in the specified date according to local time.
Math Object
The Math object is used to perform simple and complex arithmetic operations.
The Math object provides a number of properties and methods to work with Number values
PI - The value of Pi
ceil(a) - Rounds up. Returns the smallest integer greater than or equal to a
floor(a) - Rounds down. Returns the largest integer smaller than or equal to a
exp(a) - Returns ea
pow(a,b) - Returns ab
Jhalnath | GM COLLEGE
P a g e | 26
String Object
String object used to perform operations on the stored text, such as finding the length of the
string, searching for occurrence of certain characters within string, extracting a substring etc.
A String is created by using literals. A string literal is either enclosed within single quotes(‘ ‘) or
double quotes(“ “) var string1= “ Ques10“ ;
indexOf(searchtext, index) - Searches for the specified string from the beginning of the string.
lastIndexof(searchtext, index) - Searches for the specified string from the end of the string
Jhalnath | GM COLLEGE
P a g e | 27
DOM
The Document Object Model (DOM) is a programming interface for web documents. It represents
the page so that programs can change the document structure, style, and content. The DOM
represents the document as nodes and objects; that way, programming languages can interact
with the page. When a web page is loaded, the browser creates a Document Object Model of the
page.With the object model, JavaScript gets all the power it needs to create dynamic HTML:
The HTML DOM is a standard for how to get, change, add, or delete HTML elements.
Method Description
Example:
<script>
const heading = document.createElement("button");
const headingText = document.createTextNode("Click");
heading.appendChild(headingText);
document.body.appendChild(heading);
};
</script>
Jhalnath | GM COLLEGE
P a g e | 28
Method Description
Example:
<!DOCTYPE html>
<html>
<body>
<div class="example">Element1</div>
<div class="example">Element2</div>
<script>
</script>
</body>
</html>
Jhalnath | GM COLLEGE
P a g e | 29
Property Description
Event Description
onmouseover => The user moves the mouse over an HTML element
onmouseout => The user moves the mouse away from an HTML element
Jhalnath | GM COLLEGE
P a g e | 30
JSON
JSON (JavaScript Object Notation) is a text-based, human-readable data interchange format used
to exchange data between web clients and web servers. The format defines a set of structuring
rules for the representation of structured data. JSON is used as an alternative to Extensible Markup
Language (XML).
JavaScript also has a built in function for converting an object into a JSON string: JSON.stringify()
a string
a number
an object (JSON object)
an array
a boolean
null
a function
a date
undefined
Jhalnath | GM COLLEGE
P a g e | 31
JSON.parse()
A common use of JSON is to exchange data to/from a web server. When receiving data from a
web server, the data is always a string.
we need to parse the data with JSON.parse(), and the data becomes a JavaScript object.
Use the JavaScript function JSON.parse() to convert text into a JavaScript object:
1. <html>
2. <body>
3. <h2>Creating an Object from a JSON String</h2>
4. <p id="demo"></p>
5. <script>
6. const txt = '{"name":"John", "age":30, "city":"New York"}'
7. const obj = JSON.parse(txt);
8. document.getElementById("demo").innerHTML = obj.name + ", " + obj.age;
9. </script>
10. </body>
11. </html>
JSON.stringify()
When sending data to a web server, the data has to be a string. Convert a JavaScript object into a
string with JSON.stringify().
<html>
<body>
<h2>Create a JSON string from a JavaScript object.</h2>
<p id="demo"></p>
<script>
const obj = {name: "John", age: 30, city: "New York"};
const myJSON = JSON.stringify(obj);
document.getElementById("demo").innerHTML = myJSON;
Jhalnath | GM COLLEGE
P a g e | 32
</script>
</body></html>
JQuery
jQuery is an open-sourced JavaScript library that simplifies creation and navigation of web
applications. Specifically, jQuery simplifies HTML Document Object Model (DOM) manipulation,
Asynchronous JavaScript and XML (Ajax) and event handling. Additionally, jQuery incorporates
JavaScript functionalities by manipulating CSS properties to add effects such as fade-ins and outs
for website elements. jQuery is a widely used JavaScript library and is supported by thousands of
user-created plug-ins.
Inserting JQuery
following are the two different ways for adding the jQuery to html page:
Firstly, we have to download the jquery js file from the following official site of jQuery. Now, we
can include the JQuery file name with location in 'src' attribute of script tag in html file.
You can include jQuery library into your HTML code directly from a Content Delivery Network
(CDN). There are various CDNs which provide a direct link to the latest jQuery library which you
can include in your program.
Jhalnath | GM COLLEGE
P a g e | 33
jQuery Syntax
The jQuery syntax is tailor-made for selecting HTML elements and performing some action on
the element(s).
Examples:
Example:
<script>
$(document).ready(function(){
$("p").click(function(){
$(this).hide();
});
});
</script>
Important jQuery Functions
If you want to learn how jQuery can benefit you, let’s look at the essential function examples.
1. hide() Function
The hide() function hides HTML elements, making them no longer affect the HTML page. It
serves as an animation method if paired with the duration and easing parameters as well as the
callback function.
2. show() Function
The show() function displays HTML elements. It only works on elements hidden by the hide()
function. Additionally, it becomes an animation method function if given a parameter, just like
hide().
Jhalnath | GM COLLEGE
P a g e | 34
3. fadeIn() Function
The fadeIn() function modifies HTML elements’ opacity to make them appear gradually on the
HTML page. Pair it with the speed or callback function to adjust the animation’s speed and
trigger the next event once the matched elements fully appear.
4.fadeOut() Function
This jQuery function works the opposite of the fadeIn() function. Similar to hide() and show(), the
fadeIn() and fadeOut() become animation methods if given a parameter.
5. fadeToggle() Function
6. slideUp() Function
The slideUp() function hides elements with a sliding animation. Pair it with duration and easing
parameters to adjust the animation’s duration.
7. slideDown() Function
The slideDown() function displays elements with a sliding animation. Similarly, it accepts
duration and easing parameters.
Advantages of jQuery
Easy to learn: jQuery is easy to learn because it supports same JavaScript style coding.
Write less do more: jQuery provides a rich set of features that increase developers' productivity
by writing less and readable code.
Cross-browser support: jQuery provides excellent cross-browser support without writing extra
code.
Unobtrusive: jQuery is unobtrusive which allows separation of concerns by separating html and
jQuery code.g parameters.
Jhalnath | GM COLLEGE
P a g e | 35
Cookies in Javascript
Cookies are small strings of data that are stored directly in the browser. A web browser stores
this information at the time of browsing. A cookie contains the information as a string generally
in the form of a name-value pair separated by semi-colons. It maintains the state of a user and
remembers the user's information among all the web pages.
When a web server has sent a web page to a browser, the connection is shut down, and
the server forgets everything about the user.
Cookies were invented to solve the problem "how to remember information about the
user":
When a user visits a web page, his/her name can be stored in a cookie.
Next time the user visits the page, the cookie "remembers" his/her name.
Usually a cookie is designed to remember and tell a website some useful information about the
user. For example, an online bookstore might use a persistent cookie to record the authors and
titles of books user have ordered. When user return to the online bookstore, browser lets the
bookstore’s site read the cookie. The site might then compile a list of books by the same authors,
or books on related topics, and show that list to the user.
document.cookie = "username=John";
You can also add an expiry date (in UTC time).
document.cookie = "username=John; expires=Thu, 18 Dec 2013 12:00:00 UTC";
With a path parameter, you can tell the browser what path the cookie belongs to. By default, the
cookie belongs to the current page.
document.cookie = "username=John; expires=Thu, 18 Dec 2013 12:00:00 UTC; path=/";
Jhalnath | GM COLLEGE
P a g e | 36
let x = document.cookie;
<!DOCTYPE html>
<html>
<head> <title>Cookie Example</title></head>
<body>
<input type="button" value="setCookie" onclick="setCookie()">
<input type="button" value="getCookie" onclick="getCookie()">
<script>
function setCookie()
{
document.cookie="username=Mohan";
}
function getCookie()
{
if(document.cookie.length!=0)
{
alert(document.cookie);
}
else
{
alert("Cookie not available");
}
}
</script>
</body>
</html>
Jhalnath | GM COLLEGE