1
Dontha Madhusudhana
Rao
Department of Computer Science &
Engineering
2
User Interface
Design
JavaScript
What is JavaScript ?
Brendan Eich first developed JavaScript in May
1995. The language, formerly known as
Mocha, later modified to LiveScript, and is
now known simply as JavaScript, was created
to be used on the client-side of websites,
enabling the addition of dynamic and
interactive components to static HTML texts.
making it responsive to events like the
movement of the mouse, mouse click on a
certain HTML element, a button click, etc.,
using which we can improve the user
experience.
JavaScript is also being used widely in game
development and Mobile application
development.
The programs in this language are
called scripts. They can be written right in a
web page’s HTML and run automatically as
the page loads.
Scripts are provided and executed as plain
text. They don’t need special preparation or
compilation to run.
JavaScript Language Syntax
JavaScript has its own syntax and
programming style.
Syntax of a language defines rules of
writing the code in that language, what is
the correct way and what is not.
A semicolon at the end of every statement (is
Optional)
Semicolons are used to terminate the JavaScript
code statements.
In JavaScript, statements are generally followed
by a semicolon(;) which indicates termination of
the statement.
However, it is not necessary to use a
semicolon(;) at the end of the statement.
JavaScript White Spaces and Line Breaks
JavaScript interpreter ignores the tabs, spaces,
and newlines that appear in the script, except
for strings.
JavaScript Case Sensitivity
JavaScript is a case sensitive language,
which means all the keywords, function
names, variable names or identifiers should
be typed with the consistent casing of
letters.
JavaScript Comments
Comments refer to the text or code in a
program that is ignored at the time of
executing the program. Comments are used
to provide additional information in the code.
And it is considered as good practice to add
comments to your code.
// This is an single line comment and it will not be executed
/*
This is a multiline comment and everything written
inside this block will not be executed.
*/
JavaScript Statements
Statements are known as the instructions in
any programing language, these statements
are set to be executed by the computer as a
computer program.
JavaScript code is nothing but a list of these
programming statements, these statements
are collections of values, operators,
keywords, and comments.
Where to put JavaScript in
a HTML Document ?
JavaScript in <head> or <body>
You can place any number of scripts in an
HTML document.
Scripts can be placed in the <body>, or in
the <head> section of an HTML page, or in
both.
In HTML, JavaScript code is inserted
between <script> and </script> tags.
External JavaScript
External scripts are practical when the same
code is used in many different web pages.
JavaScript files have the file extension .js
To use an external script, put the name of the
script file in the src (source) attribute of a
<script> tag:
<script src="myScript.js"></script>
Document Object Model
JavaScript Object
An object is an entity having state and
behavior (properties and method). For
example: car, pen, bike, chair, glass, keyboard,
monitor etc.
JavaScript is an object-based language.
Everything is an object in JavaScript.
In real life, a car is an object.
All cars have the same properties, but the
property values differ from car to car.
All cars have the same methods, but the
methods are performed at different times.
Document Object Model
It is the object of window
The document object represents the whole
html document.
When html document is loaded in the
browser, it becomes a document object. It is
the root element that represents the html
document. It has properties and methods.
By the help of document object, we can add
dynamic content to our web page.
Properties of document object properties of
document
object that can
be accessed
and modified
by the
document
object
Methods of document object
Method Description
write("string") writes the given string on the document
getElementById( ) returns the element having the given id
value
getElementsByName( ) returns all the elements having the given
name value
getElementsByTagName( ) returns all the elements having the given
tag name
getElementsByClassName( ) returns all the elements having the given
class name
Output in JavaScript
We can get JavaScript Output in 4 simple and
different ways on a webpage
1. Using document.write( ) method
2. Using Alert Box
3. By logging on the Console
4. Using innerHTML property
<html>
<head>
<title>JavaScript</title>
</head>
<body>
<script>
document.write("This is the text written using JavaScript.") ;
</script>
</body>
</html>
<html>
<head>
<title>JavaScript</title>
</head>
<body>
<script>
window.alert("This is an alert message.") ;
</script>
</body>
</html>
<html>
<head>
<title>JavaScript</title>
<script>
console.log(“Madhu");
</script>
</head>
<body>
</body>
</html>
JavaScript Variables
Variables
Variables are containers for storing data
(storing data values)
Declare a JavaScript Variable:
1. Using var
2. Using let
3. Using const
Rules for Variable name
Variable names cannot contain spaces.
The first letter of the variable can be [a-z, A-
Z], dollar sign ($) or underscore(_)
Variable names are case sensitive.
We can not use reserved words as the name of
the variables in JavaScript.
var x = 5; let x = 5;
var y = 6; let y = 6; let carName = “BMW";
var z = x + y; let z = x + y;
const price1 = 5;
const price2 = 6;
let total = price1 + price2;
JavaScript Data Types
JavaScript Primitive Data
Types
var str = "Ferari F60";
let str1 = 'Volvo S60';
String Data Type
let x = true;
var y = false;
Boolean Data Type
var x = 45;
var y = 45.90;
Number Data Type var z = -10;
JavaScript Composite Data types
Object data type
Array data type
Function data type
JavaScript Special Data types
Undefined Data type: When a variable is just
declared and is not assigned any value, it
has undefined as its value.
var a;
Null Data type: Null data type is used to
represent no value. The Null datatype means,
the variable has been defined but it contains no
value.
var a = null;
JavaScript Operators
Arithmetic Operators
Assignment Operators
Comparison (Relational) Operators
Logical Operators
Bitwise Operators
String Operators
Ternary Operator
Arithmetic Operators
Operator Description
+ Addition
- Subtraction
* Multiplication
/ Division
% Modulus
Division
++ Increment
-- Decrement
Assignment Operators
Operator Example Same As
= x=y x=y
+= x += y x=x+y
-= x -= y x=x-y
*= x *= y x=x*y
/= x /= y x=x/y
%= x %= y x=x%y
Comparison (Relational) Operators
Operator Description
== equal to
=== equal value and equal type
!= not equal
!== not equal value or not equal type
> greater than
< less than
>= greater than or equal to
<= less than or equal to
Logical Operators
Operator Description
&& Logical
AND
|| Logical OR
! Logical Not
Bitwise Operators
Operator Description
& Bitwise AND
| Bitwise OR
^ Bitwise XOR
~ Bitwise NOT
String Operators
Operator Name Example
+ Concatenate “str1” + “str2”
Concatenate
+= str1 += “str2”
Assignment
Ternary Operator
condition ? value if true : value if false
Example:
let result = (10 > 0) ? true : false;
JavaScript Control Statements
<html>
<body>
<script>
let a = 8;
if(a < 8)
{
document.write("Number is less than 8");
}
else if (a = 8)
{
document.write("Number is equal to 8");
}
else {
document.write("Number is greater than 8");
}
</script>
</body>
</html>
<html>
<body>
<script>
for(let a = 0; a < 10; a++)
{
document.write("Current value : " + a);
document.write("<br />");
}
</script>
</body>
</html>
<html>
<head>
<script>
let a = 9;
while (a <= 10)
{
document.write("while executed <br/>");
a++;
}
</script>
</head>
<body>
</body>
</html>
<html>
<body>
<script>
let a = 10;
do
{
document.write("do executed <br/>");
a++;
}
while(a < 12)
</script>
</body>
</html>
<html>
<head>
<script>
let a = 1;
switch (a)
{
case 1: alert('case 1 has been executed');
break;
case 2:
alert("case 2 has been executed");
break;
default:
alert("default case executed");
}
</script>
</head>
</html>
Write a JavaScript program to determine if a
number is even or odd
Write a JavaScript program to determine if a
number is prime or not
Write a JavaScript program to find the factorial
of a given number
Write a JavaScript program to find the given
number is Armstrong or not
Write a JavaScript Program to print the following
pattern.
1 54321 1
22 4321 12
333 321 123
4444 21 1234
5555 1 12345
5
Write a JavaScript program to accept a
number as input and print the sum of its
digits
JavaScript Arrays
JavaScript Array is also like a data type that is
used to store one or more than one value of a
similar type or different types together
It's like a container which is used to store
values in a single variable. We can use an array
to store values of string type, or integer type,
or an object or any other valid data type in
JavaScript, or everything together.
In JavaScript, arrays are actually implemented
as objects with a special length property and
integer-like keys that act as indices.
The keys do not have to be contiguous or
ordered, meaning that you can have "holes" or
“missing indices” in the array.
// empty array
let fruits = [ ];
// Array having elements
let fruits = ["mango","apple","orange","guava"];
var fruits = [ ];
fruits[0] = "apple";
fruits[1] = "banana";
fruits[3] = "orange";
<html>
<head>
<script>
let fruits = ["mango","apple","orange","guava"];
document.write(fruits.length);
</script>
</head>
</html>
<html>
<head>
<script>
var fruits = [ ];
fruits[0] = "apple";
fruits[1] = "banana";
fruits[3] = "orange";
alert(fruits.length);
</script>
</head>
</html>
<html>
<head>
<script>
var fruits = [ ];
fruits[0] = "apple";
fruits[1] = "banana";
fruits[3] = "orange";
document.write (fruits[2]);
</script>
</head>
</html>
<html>
<head>
<script>
var fruits = [ ];
fruits[0] = "apple";
fruits[1] = "banana";
fruits[3] = "orange";
document.write (fruits);
</script>
</head>
</html>
JavaScript Functions
JavaScript Functions, just like in any other language,
is a set of statements that are used to perform a
specific task, like adding two numbers, finding the
square of a number, or any user-defined task.
Structure of a JavaScript function
function keyword
function name
function fname(parameter-1, parameter-2,...parameter-n)
{
statement 1; function parameter or input
statement 2;
statement 3; function body with the main logic
return output;
} giving output using return keyword
<html>
<head>
<script>
function add(a, b)
{
document.write(a+b);
}
add(8,8);
</script>
</head>
</html>
<html>
<head>
<script>
function add(a, b)
{
document.write(a+b);
}
add(7004,“Madhu”);
</script>
</head>
</html>
<html>
<head>
<script>
function add(a, b)
{
return a+b;
}
let result = add(8,8);
document.write(result);
</script>
</head>
</html>
<html>
<head>
<script>
function add(a, b)
{
document.write(a+b);
}
let a = parseInt(prompt("Enter number 1"));
let b = parseInt(prompt("Enter number 2"));
add(a,b);
</script>
</head>
</html>
<html>
<head>
<script>
function msg()
{
alert("Web Technologies");
}
</script>
</head>
<body>
<form>
<input type="button" onclick="msg()" value="call function">
</form>
</body>
</html>
Write a JavaScript conditional statement to find
the sign of product of three numbers using
functions
Display an alert box with the specified sign.
Sample numbers : 3, -7, 2
Output : The sign is minus (-)
Write a JavaScript conditional statement
to sort three numbers using functions
Display an alert box to show the result.
Sample numbers : 0, -1, 4
Output : 4, 0, -1
Write a JavaScript conditional statement to find
the largest of five numbers using function and
onclick event
Display an alert box to show the result.
Sample numbers : -5, -2, -6, 0, -1
Output : 0
Write a JavaScript for loop that will iterate
from 0 to 15. For each iteration, it will check
if the current number is odd or even, and
display a message to the screen.
Sample Output :
"0 is even"
"1 is odd"
"2 is even“
“3 is odd“
……............
“15 is odd”
Write a JavaScript program which iterates the
integers from 1 to 100.
But for multiples of three print “LOL" instead
of the number and for the multiples of five
print “OK". For numbers which are multiples
of both three and five print “LOL-OK".
Write a JavaScript program to read 6 subjects
marks from the student then compute the
average marks of the student. Then, this
average is used to determine the
corresponding grade.
Range Grade
<60 F
<70 D
<80 C
<90 B
<100 A
JavaScript Built-In Functions
Functions that are provided by JavaScript
itself as part of the scripting language, are
known as built-in functions. JavaScript
provides a rich set of the library that has a lot
of built-in functions.
Some examples of the built-in functions are :
alert(), prompt(), parseInt(), parseFloat()
JavaScript Math Object Methods
Math is a built-in object which includes methods
for mathematical operations. We can use the
Math object to perform simple and complex
arithmetic operations.
log( ) log10( ) exp( ) cos( ) tan( )
acos( ) asin( ) atan( ) sin( ) tanh( )
Math.ceil(x) Returns x round up to its nearest integer [4.1 to 5]
Math.floor(x) Returns x round down to its nearest integer [4.9 to 4]
Math.round(x) Returns x round to its nearest integer [4.4 to 4 , 4.5 to 5 ]
Math.sign(x) Returns -1 ,0 ,1 , if given negative, zero, positive number
Math.pow(x, y) returns the value of x to the power of y
Math.sqrt(x) returns the square root of x
Math.abs(x) returns the absolute (positive) value of x
Math.min() can be used to find the lowest or highest value in a list of
Math.max() arguments
Math.random() returns a random number between 0 (inclusive), and 1
(exclusive)
JavaScript String Object Methods
Methods Description
charAt( ) It provides the char value present at the specified index.
concat( ) It provides a combination of two or more strings.
indexOf( ) It provides the position of a char value present in the
given string.
lastIndexOf( ) It provides the position of a char value present in the
given string by searching a character from the last
position.
search( ) It searches a specified regular expression in a given string
and returns its position if a match occurs.
match( ) It searches a specified regular expression in a given string
and returns that regular expression if a match occurs.
replace( ) It replaces a given string with the specified replacement.
substr( ) It is used to fetch the part of the given string on the basis
of the specified starting position and length.
slice( ) It is used to fetch the part of the given string on the basis
of starting and ending index
toLowerCase( ) It converts the given string into lowercase letter.
toUpperCase( ) It converts the given string into uppercase letter.
JavaScript Array Object Methods
pop( ) It removes and returns the last element of an array.
push( ) It adds one or more elements to the end of an array.
shift( ) It removes and returns the first element of an array
unshift( ) It adds one or more elements in the beginning of the
given array
reverse( ) It reverses the elements of given array.
sort( ) It returns the element of the given array in a sorted
order.
concat( ) It returns a new array object that contains two or more
merged arrays.
slice( ) It returns a new array containing the copy of the part
of the given array based on the starting and ending
index numbers
splice( ) It add/remove elements to/from the given array based
on the provided index numbers
indexOf( ) It searches the specified element in the given array
and returns the index of the first match.
lastIndexOf( ) It searches the specified element in the given array
and returns the index of the last match.
HTML Document Object Model
Accessing HTML elements by
document object and its methods
<body>
<form name="addition">
Number 1:<input type="text" name="num1"><br>
Number 2:<input type="text" name="num2"><br><br>
<input type="button" onclick="add()" value="Calculate">
</form>
</body>
<head>
<script>
function add( )
{
let a = parseInt(document.addition.num1.value);
let b = parseInt(document.addition.num2.value);
let result = a+b;
alert("the result is"+result);
}
</script>
</head>
getElementById( )
<form name="addition">
Number 1:<input type="text" id="one" name="num1"><br>
Number 2:<input type="text" id="two" name="num2">
<br><br>
<input type="button" onclick="add()" value="Calculate">
</form>
<head>
<script>
function add()
{
var a = parseInt(document.getElementById("one").value);
var b = parseInt(document.getElementById("two").value);
alert(a+b);
}
</script>
</head>
<head>
<script>
function add()
{
var a = parseInt(document.getElementById("one").value);
var b = parseInt(document.getElementById("two").value);
var result = a+b;
document.getElementById("details").innerHTML = result;
}
</script>
</head>
<body>
<p id="details"></p>
</body>
getElementsByName( )
<body>
<form name="details">
<p>First Name: <input type="text" name="fname"></p>
<p>Last Name: <input type="text" name="fname"></p>
<input type="button" onclick="read()" value="Display">
</form>
<br>
<p id="details"></p>
</body>
<head>
<script>
function read()
{
let elements = document.getElementsByName("fname");
document.getElementById("details").innerHTML = elements[0].value;
}
</script>
</head>
getElementsByTagName( )
<body>
<form name="addition">
Number 1:<input type="text" name="num1"><br>
Number 2:<input type="text" name="num2"> <br><br>
<input type="button" onclick="add()" value="Display">
</form>
<p id="details"></p>
</body>
<head>
<script>
function add()
{
let elements = document.getElementsByTagName("input");
document.getElementById("details").innerHTML = elements[0].value;
}
</script>
</head>
getElementsByClassName( )
<body>
<form name="addition">
Number 1:<input type="text" class="one" name="num1"><br>
Number 2:<input type="text" class="one" name="num2">
<br><br>
<input type="button" onclick="add()" value=“Calculate">
</form>
</body>
<script>
function add()
{
let elements = document.getElementsByClassName("one");
let a = parseInt(elements[0].value);
let b = parseInt(elements[1].value);
alert(a+b);
}
</script>
HTML Form Validations
JavaScript Validations
It is important to validate the form submitted by
the user because it can have inappropriate
values. So, validation is must to authenticate
user.
JavaScript provides facility to validate the form
on the client-side so data processing will be
faster than server-side validation.
Through JavaScript, we can validate name,
avaScript Form Validation for Empty Inputs
<script>
function validateForm( )
{
var x = document.forms.name.value;
if (x == "" || x == null)
{
alert("Name must be filled out");
return false;
}
}
</script>
JavaScript Form Validation for required
Length
<script>
function validate( )
{
var x=document.myForm.name.value;
if (x.length<5)
{
alert("The field cannot contain less than 5 characters!")
return false;
}
else {
return true
}
}
</script>
Java Script Form E-mail Validation
A regular expression is a pattern of characters.
<script>
let text = “Amrita University";
let pattern = /Amrita/;
let result = text.match(pattern);
document.getElementById(“value").innerHTML = result;
</script>
regular expression for Email
/[a-zA-Z0-9._-] +@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}/;
/[a-zA-Z0-9._-] +@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}/;
/[a-zA-Z0-9._-]+: Means that the email address must
begin with alpha-numeric characters (both
lowercase and uppercase characters are
allowed). It may have periods, underscores and
hyphens.
/[a-zA-Z0-9._-] +@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}/;
@: There must be a ‘@’ symbol after
initial characters.
/[a-zA-Z0-9._-] +@ [a-zA-Z0-9.-]+ \.[a-zA-Z]{2,4}/;
[a-zA-Z0-9.-]+: After the ‘@’ sign there must be
some alpha-numeric characters. It can also
contain period (‘.’) and hyphens(‘-‘).
/[a-zA-Z0-9._-] +@ [a-zA-Z0-9.-]+ \. [a-zA-Z]{2,4}/;
After the second group of characters there
must be a period (‘.’). This is to separate
domain and subdomain names.
/[a-zA-Z0-9._-] +@ [a-zA-Z0-9.-]+ \. [a-zA-Z]{2,4}/;
[a-zA-Z]{2,4}/: Finally, the email address must end with
two to four alphabets. Having a-z and A-Z means that
both lowercase and uppercase letters are allowed.
{2,4} indicates the minimum and maximum number of
characters. This will allow domain names with 2, 3 and
4 characters e.g.; us, tx, org, com, net, wxyz).
<body>
<form name="form1" action="#">
<input type="text" name="text1" />
<br />
<input type="submit" value= “Submit”
onclick = "validateEmail(document.form1.text1)">
</body>
function validateEmail(inputtext)
{
var mailformat = /[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}/;
if(inputtext.value.match(mailformat))
{
alert("Valid email address!");
return true;
}
else
{
alert("You have entered an invalid email address!");
return false;
}
JavaScript Events
The change in the state of an object is
known as an Event.
In HTML, there are various events which
represents that some activity is performed
by the user or by the browser.
This process of reacting over the events is
called Event Handling.
JavaScript handles events using Event
Handlers.
JavaScript Events
Mouse Events
Keyboard Events
Form Events
Mouse Events
Event Event Handler Description
Performed
click onclick When mouse click on an element
mouseover onmouseover When the cursor of the mouse
comes over the element
mouseout onmouseout When the cursor of the mouse
leaves an element
mousedown onmousedown When the mouse button is
pressed over the element
mouseup onmouseup When the mouse button is
released over the element
Keyboard Events
Event Event Description
Performed Handler
Key down onkeydown When the user
& & press(hold pressing) and
Key up onkeyup then release the key
Key Press onkeypress When the user press the
key
Form Events
Event Event Description
Performed Handler
submit onsubmit When the user submits the
form
focus onfocus When the user focuses on a
form element
blur onblur When the focus is away from
a form element
change onchange When the user modifies or
changes the value of a form
element
Thank You