BE 5 IT GECBVN BharatVainsh Unit 5 (JavaScript) WD 3151606 2023
BE 5 IT GECBVN BharatVainsh Unit 5 (JavaScript) WD 3151606 2023
UNIVERSITY
Chandkheda, Ahmedabad
Affiliated
GOVERNMENT ENGINEERING COLLEGE
BHAVNAGAR
DEPARTMENT OF INFORMATION TECHNOLOGY
Under subject of
Web Development (3151606)
B. E. III, Semester –V (Information Technology)
UNIT-3
JavaScript
Prof.Bharat Vainsh
Academic year
2023
Ch#3
JavaScript
Overview
1. HTML to define the content of web pages
• like Builder
• It decides which element has to be display.
10
X = 10;
X
Representation of Primitive type
obj 65530
Representation of object type
Literals
• There are two types of literals used in JavaScript
1. Numeric literals
e.g. 10
10.3
10.0
10E3
10.2E4
10e-3
2. String literals
e.g. ‘ Rain Rain come soon’
Variable declaration
• Declare variable using reserved word var.
• Value of variable can be anything.
• It can be numeric or string or boolean
<html>
<head> <title> Variables in javascript </title> </head>
<body>
<script type=“text/javascript”> Variable declaration is done using var.
var a,b,c; Note that there is no data type required.
var string;
a=2;
b=3;
c=a+b;
output
string = “The result=“;
document.write (“ addition of 2 & 3.” + “</br>”); Addition of 2 & 3.
document.write ( string); The result=5
document.write (c);
</scipt> <body> </html>
Operators
Type Operator Meaning Example
+ Addition or Unary plus C=a+b
- Subtraction or Unary minus C=a-b
Arithmetic
* Multiplication C=a*b
/ Division C=a/b
% Mod C=a%b
< Less than a< 4
<= Less than equal to b <= 10
• if statement
• while
• do – while
• for
• switch case
• break
• Continue
Selection Statement
• if the syntax of if is
if (condition)
statement if the condition is true
• if ….. else the syntax for if….else
if (condition)
statement if the condition is true
else
statement if the condition is false
• if…..else if the syntax of if….else if
if (condition)
statement if the condition is true
else if (condition)
statement if another condition is true
else if (condition)
statement if another condition is true
…….
else statement
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, ...)
Code
function myFunction(p1, p2) {
return p1 * p2;
}
Conti…
• The code to be executed, by the function, is placed inside curly brackets.
• When JavaScript reaches a return statement, the function will stop
executing.
• Separate functions can be created for each separate task.
• Ultimately helps in finding the bug from the program efficiently.
• Can define the function any where in the script either in head or body or
in both .
a. Function declaration
b. Function call
c. Returning value from the function
d. Passing the parameters to the function
e. Passing an array to the function
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
E.g. objectName.propertyName
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
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>
DHTML
• Dynamic HyperText Markup Language (DHTML)
HTML DHTML
Creation of HTML web pages is simple Creation of DHTML is complex but more
but not interactive. interactive.
JavaScript Array
• JS Array
• Array is special type of variable which can store
multiple values as well as each value is associated
with numeric index starting with zero.
• Value
index 010 120 230 340 450
That allows to store more that one value or a group
of values under a single variable name.
Array can store any valid value.
JavaScript Array
Java script array literal
• Var emp=[“X”,”Y”,”Z”];
• For(i=0;i<emp.length;i++){
• Document.write(emp[i] +”</br>”);
• }
Javascript array directly new keyword
• Var I;
• Var emp =new Array();
• Emp[0]=“x”;
• Javascript array constructor new keyword
• Var emp=new Array(“x”,”y”,”z”);
Creating Array
• Var myarray=[element 0,element 1…element N]
• Var colors=[“red”,”green”,”blue”];
• Example
var fruits=[“Apple”,”Banana”,”Mango”];
document.write(fruits.length);
for(var i=0;i<fruits.length;i++)
{ document.write(fruits[i]+”<br>”);
}
Array
• How to store some array elements in array.
• A= new Array(5); //creation of array
For(i=0;i<5;i++)
{a[i]=i;
document.write(a[i]+”<br>”);//displaing array
}
B=new Array(11,22,33,44);
Days=new Array();
Days[0]=“sunday”;
For(in days)
{ document.write(Days[i]+”</br>”);
}
Events
• What is an Event ?
• JavaScript's interaction with HTML is handled
through events that occur when the user or
the browser manipulates a page.
• When the page loads, it is called an event.
When the user clicks a button, that click too is
an event. Other examples include events like
pressing any key, closing a window, resizing a
window, etc.
Events
• An activity that represent change in the environment.
• E.g. Mouse click, pressing particular key of keyboard
• Such events are called Intrinsic events.
• Event handler is a script that gets executed in
response to these events.
• Javascript support such special typeof programming in
which events may occur and these events get
responded by executing the event handlers.
• Events are specified in lowercase letters and these are
case-sensitive.
• The process of connecting event handler to an event is
called event Registration.
• Developers can use these events to execute
JavaScript coded responses, which cause
buttons to close windows, messages to be
displayed to users, data to be validated, and
virtually any other type of response
imaginable.
• Events are a part of the Document Object
Model (DOM) Level 3 and every HTML
element contains a set of events which can
trigger JavaScript Code.
Event, Attribute and Tags
Events Attributes Meaning Associated Tags
blur onblur Losing the focus <button>
<input>
<a>
<textarea>
<select>
change onchange On occurence of <input>
some change <textarea>
<select>
click onclick When user clicks <a>
the mouse button <input>
dbclick ondbclick When user double <a>
clicks the mouse <input>
<button>
focus onfocus When user acquires <a>
the input focus <input>
<select>
<textarea>
Conti...
Event Attribute Meaning Associated Tags
keyup onkeyup When user releases <input>
the from the <button>
keyboard <textarea>
keydown onkeydown When user presses <input>
the key <button>
<textarea>
mousedown onmousedown When user clicks Form element such
the left mouse as input,button etc
button
mouseup onmouseup When user releases Form element such
the left mouse as input,button
button etc..
mousemove onmousemove When user moves Form element...
the mouse
Conti...
Event Attribute Meaning Associated Tags
load onload After getting the <body>
document loaded
reset onreset When the reset <form>
button is clicked
submit onsubmit When the submit <form>
button is clicked
select onselect On selection <input>
<textarea>
<body>
<form>
<input type="button" name="button" value="Go"
onclick="hiThere()"></input>
</form>
</body>
</html>
Example-2
<script>
var a = 0;
var b = 0;
var c = 0;
function changeBackground()
{
var x = document.getElementById('bg');
bg.style.backgroundColor = 'rgb('+a+', '+b+', '+c+')';
a += 1;
b += a + 1;
c += b + 1;
if (a > 255) a = a - b;
if (b > 255) b = a;
if (c > 255) c = b;
}
</script>
</head>
<body>
<input id="bg" onkeyup="changeBackground()" placeholder="write something"
style="color:#fff">
</body>
Example-3
<script>
function hov() {
var e = document.getElementById('hover');
e.style.display = 'none'; }
</script>
</head>
<body>
<div id="hover" onmouseover="hov()"
style="background-
color:red;height:300px;width:300px;">
</div>
</body>
Example-4
<html>
<head></head>
<title></title>
<body>
<input type="number" onchange="alert(this.value)" >
</body>
</html>
Example-5
<body>
<!-- <img onload="alert('Image completely loaded')"
alt="Smart Learning-Logo"
src="https://bharatvainshit.in">-->
<script>
function sample()
{
alert("welcome");
}
</script>
<body onload="sample()">
</body>
JavaScript Cookies
What is a Cookie
A cookie is a small text file that lets you store a small amount of
data (nearly 4KB) on the user's computer. They are typically used
for keeping track of information such as user preferences that
the site can retrieve to personalize the page when user visits the
website next time.
Cookies are an old client-side storage mechanism that was
originally designed for use by server-side scripting languages
such as PHP, ASP, etc. However, cookies can also be created,
accessed, and modified directly using JavaScript, but the process
is little bit complicated and messy.
Tip: A cookie can be up to 4 KB, including its name and values,
cookies that exceed this length are trimmed to fit. Also, each
time the browser requests a page to the server, all the data in
the cookie is automatically sent to the server within the request.
Warning: Don't store sensitive data such as a password or credit
card information in cookies since it could potentially be
manipulated by the malicious user.
JavaScript Cookies
Creating a Cookie in JavaScript
In JavaScript, you can create, read, and delete
cookies with the document.cookie property.
This property represents all the cookies
associated with a document.
To create or store a new cookie, assign a
name=value string to this property, like this:
document.cookie = "firstName=James";
A cookie value cannot contain semicolons,
commas, or spaces.
JavaScript Cookies
ExampleTry this code »
function setCookie(name, value, daysToLive) {
// Encode value in order to escape semicolons, commas, and whitespace
var cookie = name + "=" + encodeURIComponent(value);
document.cookie = cookie;
}
}
By default, a cookie is available to all web pages in the same directory or any
subdirectories of that directory. However, if you specify a path the cookie is
available to all web pages in the specified path and to all web pages in all
subdirectories of that path.
For example, if the path is set to / the cookie is available throughout a
website, regardless of which page creates the cookie.
ExampleTry this code »
function checkCookie() {
// Get cookie using our custom function
var firstName = getCookie("firstName");
if(firstName != "") {
alert("Welcome again, " + firstName); }
else {
firstName = prompt("Please enter your first name:");
if(firstName != "" && firstName != null) {
// Set cookie using our custom function
setCookie("firstName", firstName, 30); } }}
Updating a Cookie
The only way to update or modify a cookie is to create another cookie with
the same name and path as an existing one. Creating a cookie with the same
name but with a different path then that of an existing one will add an
additional cookie. Here's an example:
<body>
<form action = "/cgi-bin/test.cgi" name = "myForm" onsubmit =
"return(validate());">
<table cellspacing = "2" cellpadding = "2" border = "1">
<tr>
<td align = "right">Name</td>
<td><input type = "text" name = "Name" /></td>
</tr>
<tr>
<td align = "right">EMail</td>
<td><input type = "text" name = "EMail" /></td>
</tr>
<tr>
<td align = "right">Zip Code</td>
<td><input type = "text" name = "Zip" /></td>
</tr>
<tr>
<td align = "right">Country</td>
<td>
<select name = "Country">
<option value = "-1" selected>[choose yours]</option>
<option value = "1">USA</option>
<option value = "2">UK</option>
<option value = "3">INDIA</option>
</select>
</td>
</tr>
<tr>
<td align = "right"></td>
<td><input type = "submit" value = "Submit" /></td>
</tr>
</table>
<script type = "text/javascript">
<!--
// Form validation code will come here.
function validate() {
Example
// Literal syntax
var regex = /^Mr\./;
// Constructor syntax
var regex = new RegExp("^Mr\\.");
As you can see, the regular expression literal syntax is shorter and easier to
read. Therefore it is preferable to use the literal syntax. We'll also use it
throughout this tutorial.
Example
Storing data in local storage
// Storing data:
myObj = {name: "John", age: 31, city: "New York"};
myJSON = JSON.stringify(myObj);
localStorage.setItem("testJSON", myJSON);
// Retrieving data:
text = localStorage.getItem("testJSON");
obj = JSON.parse(text);
document.getElementById("demo").innerHTML = obj.name;
Object concepts in JavaScript
JavaScript is an Object Oriented Programming (OOP) language. A
programming language can be called object-oriented if it
provides four basic capabilities to developers
Inheritance − the capability of a class to rely upon another class (or number of
classes) for some of its properties and methods.
The properties assigned to the object are not variables and are not
defined with the var keyword.
The 'with' Keyword
The ‘with’ keyword is used as a kind of shorthand for referencing
an object's properties or methods.
The properties and methods for the object can be used without
naming the object.
Syntax
The syntax for with object is as follows −
with (object) {
properties used without the object name and dot
}
References
• E-Books:
Web Technologies, Black Book, Dreamtech Press
PHP: The Complete Reference By Steven Holzner, McGrawhill
• Website :
1. https://www.bharatvainsh.in/
2. https://smarteportal.blogspot.com/
3. https://www.w3schools.com/
4. https://www.javatpoint.com/
5. https://www.studentstutorial.com/
6. https://www.tutorialspoint.com/seo/index.htm
7. https://javascript.info/
8. https://www.guru99.com/
9. https://www.tutorialspoint.com/php/
10. https://www.codecademy.com/catalog/subject/web-development