WT Unit-2 Javascript
WT Unit-2 Javascript
JAVASCRIPT
J Vishnu Priyanka
Assistant Professor©
Dept of CSE
RGUKT-SRIKAKULAM.
INTRODUCTION
<button type="button"
onclick='document.getElementById("demo").innerHTML =
"Hello JavaScript!"'>Click Me!</button>
</body>
</html>
JavaScript Can Change HTML Attribute Values
In this example JavaScript changes the value of the src (source) attribute of an <img> tag:
Example:
<!DOCTYPE html>
<html>
<body>
<p>In this case JavaScript changes the value of the src (source) attribute of an image.</p>
</body>
</html>
JavaScript Can Change HTML Styles (CSS)
<!DOCTYPE html>
<html>
<body>
<h2>What Can JavaScript Do?</h2>
<p id="demo">JavaScript can change the style of an HTML
element.</p>
<button type="button"
onclick="document.getElementById('demo').style.fontSize='35
px'">Click Me!</button>
</body>
</html>
JavaScript Can Hide HTML Elements
<!DOCTYPE html>
<html>
<body>
<h2>What Can JavaScript Do?</h2>
<button type="button"
onclick="document.getElementById('demo').style.display='none
'">Click Me!</button>
</body>
</html>
JavaScript Can Show HTML Elements
<!DOCTYPE html>
<html>
<body>
<h2>What Can JavaScript Do?</h2>
<p>JavaScript can show hidden HTML elements.</p>
<button type="button"
onclick="document.getElementById('demo').style.display='block'">Click
Me!</button>
</body>
</html>
The <script> Tag
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript in Body</h2>
<p id="demo"></p>
<script>
document.getElementById("demo").innerHTML = "My First JavaScript";
</script>
</body>
</html>
JavaScript in <head>
<!DOCTYPE html>
<html>
<head>
<script>
function myFunction() {
document.getElementById("demo").innerHTML = "Paragraph changed.";
}
</script>
</head>
<body>
<h2>JavaScript in Head</h2>
</body>
</html>
JavaScript in <body>
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript in Body</h2>
<script>
function myFunction() {
document.getElementById("demo").innerHTML = "Paragraph changed.";
}
</script>
</body>
</html>
JavaScript Output
JavaScript can "display" data in different ways:
Using innerHTML
To access an HTML element, JavaScript can use the
document.getElementById(id) method.
The id attribute defines the HTML element. The innerHTML
property defines the HTML content:
Using document.write()
For testing purposes, it is convenient to use document.write():
<!DOCTYPE html>
<html>
<body>
<script>
document.write(5 + 6);
</script>
</body>
</html>
JavaScript Statements
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Statements</h2>
<p id="demo"></p>
<script>
var x, y, z; // Statement 1
x = 5; // Statement 2
y = 6; // Statement 3
z = x + y; // Statement 4
document.getElementById("demo").innerHTML =
"The value of z is " + z + ".";
</script>
</body>
</html>
Advantages of JavaScript:
Less server interaction
Immediate feedback to the visitors
Increased interactivity
Java Script is relatively secure.
Points to remember:
JavaScript is case-sensitive
Each line of code is terminated by a semicolon
Variables are declared using the keyword var
JavaScript and HTML Page
Having written some JavaScript, we need to include it in an
HTML page.
We can‟t execute these scripts from a command line, as the
interpreter is part of the browser.
The script is included in the web page and run by the browser,
usually as soon as the page has been loaded.
The browser is able to debug the script and can display errors.
<html>
<head>
<script language="javascript">
function show_alert()
{
alert("Hi! This is alert box!!");
}
</script>
</head>
<body>
<input type="button"onclick="show_alert()" value=“Display alert box" >
</input>
</body>
</html>
OUTPUT
Confirm(“string”)
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Confirm Box</h2>
<button onclick="myFunction()">Try it</button>
<p id="demo"></p>
<script>
function myFunction() {
var txt;
if (confirm("Press a button!")) {
txt = "You pressed OK!";
} else {
txt = "You pressed Cancel!";
}
document.getElementById("demo").innerHTML = txt;
}
</script>
</body>
PROMPT(“STRING”)
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Prompt</h2>
<button onclick="myFunction()">Try it</button>
<p id="demo"></p>
<script>
function myFunction() {
let text;
let person = prompt("Please enter your name:", "Harry Potter");
if (person == null || person == "") {
text = "User cancelled the prompt.";
} else {
text = "Hello " + person + "! How are you today?";
}
document.getElementById("demo").innerHTML = text;
}
</script>
</body>
</html>
JavaScript Programming Elements
Most high-level languages, including C and Java, are strongly typed. That
is, a variable must be declared before it is used, and its type must be included
in its declaration. Once a variable is declared, its type cannot be changed.
As the JavaScript is weakly typed language, data types are not explicitly
declared.
Example:
var num;
num = 3;
num = "San Diego";
First, when the variable num is declared, it is empty. Its data type
is actually the type undefined.
<h2>JavaScript Variables</h2>
<p id="demo"></p>
<script>
var a = 5;
var b = 6;
var c = a + b;
document.getElementById("demo").innerHTML =
"The value of c is: " + c;
</script>
</body>
</html>
DATATYPES
JavaScript supports five primitive data types:
Number
String
Boolean
Undefined
Null
These types are referred to as primitive types because they are the basic
building blocks from which more complex types can be built.
Of the five, only number, string, and boolean are real data types in the sense
of actually storing data.
Undefined and null are types that arise under special circumstances.
Primitive Data Types
Numbers
Strings
Boolean (True, False)
Composite Data Types
Arrays
Objects
Numbers - A number can be either an integer or a decimal
Ans = q + x + y;
var z = “xyz”;
Ans => 179
var q = “17”;
Decimal: The usual numbers which are having the base 10 are
the decimal numbers
Octal: Octal literals begin with a leading zero, and they consist
of digits from zero through seven. The following are all valid
octal literals:
00 0777 024513600
<h2>JavaScript</h2>
<p>When adding a number and a string, JavaScript will treat the number as a
string.</p>
<p id="demo"></p>
<script>
var x = 16 + "Volvo";
document.getElementById("demo").innerHTML = x;
</script>
</body>
</html>
JavaScript Strings
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Strings</h2>
<p>Strings are written with quotes. You can use single or double quotes:</p>
<p id="demo"></p>
<script>
var carName1 = "Volvo XC60";
var carName2 = 'Volvo XC60';
document.getElementById("demo").innerHTML =
carName1 + "<br>" +
carName2;
</script>
</body>
</html>
JavaScript Numbers
JavaScript has only one type of numbers.
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Numbers</h2>
<p id="demo"></p>
<script>
var x1 = 34.00;
var x2 = 34;
var x3 = 3.14;
document.getElementById("demo").innerHTML =
x1 + "<br>" + x2 + "<br>" + x3;
</script>
</body>
</html>
JavaScript Booleans
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Booleans</h2>
<p id="demo"></p>
<script>
var x = 5;
var y = 5;
var z = 6;
document.getElementById("demo").innerHTML =
(x == y) + "<br>" + (x == z);
</script>
</body>
</html>
JavaScript Arrays
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Arrays</h2>
<p>Array indexes are zero-based, which means the first item is [0].</p>
<p id="demo"></p>
<script>
var cars = ["Saab","Volvo","BMW"];
document.getElementById("demo").innerHTML = cars[0];
</script>
</body>
</html>
JavaScript Objects
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Objects</h2>
<p id="demo"></p>
<script>
var person = {
firstName : "John",
lastName : "Doe",
age : 50,
eyeColor : "blue"
};
document.getElementById("demo").innerHTML =
person.firstName + " is " + person.age + " years old.";
</script>
</body>
</html>
The typeof Operator
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript typeof</h2>
<p>The typeof operator returns the type of a variable or an expression.</p>
<p id="demo"></p>
<script>
document.getElementById("demo").innerHTML =
typeof "" + "<br>" +
typeof "John" + "<br>" +
typeof "John Doe";
</script>
</body>
</html>
Primitive Data
A primitive data value is a single simple data value with no additional properties and methods.
The typeof operator can return one of these primitive types:
string
number
Boolean
undefined
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript typeof</h2>
<p>The typeof operator returns the type of a variable or an expression.</p>
<p id="demo"></p>
<script>
document.getElementById("demo").innerHTML =
typeof "john" + "<br>" +
typeof 3.14 + "<br>" +
typeof true + "<br>" +
typeof false + "<br>" +
typeof x;
</script>
</body>
</html>
Operators in JavaScript
The operators in JavaScript can be classified as follows:
Arithmetic operators
Relational operators
Logical operators
Assignment operators
1. Arithmetic operators
Example:
<html>
<body>
<script language="JavaScript">
<!--
var a = 5;
++a;
alert("The value of a = " + a );
-->
</script>
</body>
</html>
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Operators</h2>
<p id="demo"></p>
<script>
let text1 = "RGUKT";
let text2 = "SRIKAKULAM";
document.getElementById("demo").innerHTML = text1 + " " + text2;
</script>
</body>
</html>
EXAMPLE:
<html>
<body>
document.write("a + b = ");
result = a + b;
document.write(result);
document.write(linebreak);
document.write("a - b = ");
result = a - b;
document.write(result);
document.write(linebreak);
document.write("a / b = ");
result = a / b;
document.write(result);
document.write(linebreak);
document.write("a % b = ");
result = a % b;
document.write(result);
document.write(linebreak);
document.write("a + b + c = ");
result = a + b + c;
document.write(result);
document.write(linebreak);
a = ++a;
document.write("++a = ");
result = ++a;
document.write(result);
document.write(linebreak);
b = --b;
document.write("--b = ");
result = --b;
document.write(result);
document.write(linebreak);
//-->
</script>
CREATING AN ARRAY:
There are several different ways to create an array in JavaScript
Using the Array() constructor:
Adding Elements
To add a new element to an array, simply assign a value to it
Example:
var a = new Array(10);
a[7] = 17;
ARRAY LENGTH
All arrays created in JavaScript have a special length property that specifies how
many elements the array contains
Example:
var colors = [“red”, “green”, “blue”];
colors.length => 3
Example:
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Arrays</h2>
<p>JavaScript array elements are accessed using numeric indexes
(starting from 0).</p>
<p id="demo"></p>
<script>
var campus = ["srikakulam", "nuzvid", "rkvalley"];
campus[1] = "Ongole";
document.getElementById("demo").innerHTML = campus;
</script>
</body>
</html>
Array Properties and Methods
The real strength of JavaScript arrays are the built-in array properties and methods:
var x = cars.length; // The length property returns the number of elements
var y = cars.sort(); // The sort() method sorts arrays
EXAMPLE:
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Arrays</h2>
<p>The length property returns the length of an array.</p>
<p id="demo"></p>
<script>
var departments = ["cse", "ece", "mechanical", "eee"];
document.getElementById("demo").innerHTML = departments.length;
</script>
</body>
</html>
Accessing the Last Array Element
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Arrays</h2>
<p>JavaScript array elements are accesses using numeric indexes (starting from 0).</p>
<p id="demo"></p>
<script>
var departments = ["cse", "eee", "ece", "Mechanical"];
var last = departments[departments.length-1];
document.getElementById("demo").innerHTML = last;
</script>
</body>
</html>
Adding Array Elements
The easiest way to add a new element to an array is using the push() method:
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Arrays</h2>
<p id="demo"></p>
<script>
var campus = ["Nuzvid", "RKValley", "Srikakulam"];
document.getElementById("demo").innerHTML = campus;
function myFunction() {
campus.push("ongole");
document.getElementById("demo").innerHTML = campus;
}
</script>
</body>
</html>
Associative Arrays
Many programming languages support arrays with named indexes.
Arrays with named indexes are called associative arrays (or hashes).
EXAMPLE:
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Arrays</h2>
<p id="demo"></p>
<script>
var campus = [];
campus[0] = "Rgukt";
campus[1] = "srikakulam";
campus[2] = 1;
document.getElementById("demo").innerHTML =
campus[0] + " " + campus.length;
</script>
</body>
</html>
Functions
Functions are a collection of JavaScript statements that performs a specified task
Functions are used whenever it is necessary to repeat an operation
Functions have inputs and outputs
The inputs are passed into the function and are known as arguments or parameters
Think of a function as a “black box” which performs an operation
function_square.html:
<html>
<head>
<title>Functions</title>
<script src="square.js">
</script>
</head>
<body>
<script>
var x = prompt("Enter a positive integer value",0);
document.writeln("the value is ", square(x));
</script>
</body>
</html>
square.js:
function square(number)
{
return number * number;
}
EXAMPLE:FACTORIAL
<head>
<title>Functions</title>
</head>
<body>
<script>
function factorial(x) {
if (x <= 0)
return(1);
else
return( x * factorial(x-1));
}
var x = prompt("Enter a positive integer
value",0);
document.write("The factorial of " + x + " is
" + factorial(x));
</script>
</body>
EXAMPLE:
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Functions</h2>
<p>This example calls a function which performs a calculation and returns the result:</p>
<p id="demo"></p>
<script>
var x = myFunction(4, 3);
document.getElementById("demo").innerHTML = x;
function myFunction(a, b) {
return a * b;
}
</script>
</body>
</html>
JavaScript Functions
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Functions</h2>
<p>This example calls a function which performs a calculation, and returns the result:</p>
<p id="demo"></p>
<script>
function myFunction(p1, p2) {
return p1 * p2;
}
document.getElementById("demo").innerHTML = myFunction(4, 3);
</script>
</body>
</html>
CONDITIONAL STATEMENTS
There are three basic types of control structures in JavaScript: the if statement, the
while loop, and the for loop
Each control structure manipulates a block of JavaScript expressions beginning with
{ and ending with }
In JavaScript we have the following conditional statements:
if to specify a block of code to be executed, if the specified condition is true
else to specify a block of code to be executed, if the same condition is false
else if to specify a new condition to test, if the first condition is false
switch to specify many alternative blocks of code to be executed
The If Statement
If ( x = = 10)
The if statement
allows { y = x*x;
JavaScript }
programmers to else
a make decision
{ x = 0;
}
EXAMPLE
<html>
<body>
<script type = "text/javascript">
</script>
</body>
</html>
if...else statement
The 'if...else' statement is the next form of control statement that allows
JavaScript to execute statements in a more controlled way.
Syntax
if (expression){
Statement(s) to be executed if expression is true }
Else{
Statement(s) to be executed if expression is false }
Here JavaScript expression is evaluated. If the resulting value is true, the given
statement(s) in the ‘if’ block, are executed. If the expression is false, then the
given statement(s) in the else block are executed.
EXAMPLE
<html>
<body>
<script type = "text/javascript">
</script>
</body>
</html>
if...else if... statement
The if...else if... statement is an advanced form of if…else that allows JavaScript to make
a correct decision out of several conditions.
Syntax
The syntax of an if-else-if statement is as follows −
if (expression 1) {
Statement(s) to be executed if expression 1 is true
} else if (expression 2) {
Statement(s) to be executed if expression 2 is true
} else if (expression 3) {
Statement(s) to be executed if expression 3 is true
} else {
Statement(s) to be executed if no expression is true
}
if is a part of the else clause of the previous statement. Statement(s) are executed based
on the true condition, if none of the conditions is true, then the else block is executed.
EXAMPLE
<html>
<body>
<script type = "text/javascript">
</script>
</body>
</html>
SWITCH CASE
The objective of a switch statement is to give an expression to evaluate and several
different statements to execute based on the value of the expression. The interpreter
checks each case against the value of the expression until a match is found. If nothing
matches, a default condition will be used.
SYNTAX:
switch (expression) {
case condition 1: statement(s)
break;
default: statement(s)
}
Repeat Loops
A repeat loop is a group of statements that is repeated until a specified condition is met
Repeat loops are very powerful programming tools; They allow for more efficient
program design and are ideally suited for working with arrays.
count = 0;
The while loop is
used to execute a while (count <= 10) {
block of code document.write(count);
while a certain count++;
condition is true
}
EXAMPLE
<!DOCTYPE html>
<html>
<body>
<p id="demo"></p>
<script>
let text = "";
let i = 0;
while (i < 10) {
text += "<br>The number is " + i;
i++;
}
document.getElementById("demo").innerHTML = text;
</script>
</body>
</html>
THE FOR LOOP
The 'for' loop is the most compact form of looping. It includes the following three important
parts −
The loop initialization where we initialize our counter to a starting value. The
initialization statement is executed before the loop begins.
The test statement which will test if a given condition is true or not. If the condition is
true, then the code given inside the loop will be executed, otherwise the control will
come out of the loop.
The iteration statement where you can increase or decrease your counter.
You can put all the three parts in a single line separated by semicolons.
Syntax
The syntax of for loop is JavaScript is as follows −
for (initialization; test condition; iteration statement) {
Statement(s) to be executed if test condition is true
}
Example: For Loop
// Print the numbers 1 through i=1 initializes the counter
10 i<=10 is the target
value
for (i=1; i<= 10; i++) i++ updates the
document.write(i); counter at the end
of the loop
<SCRIPT>
<SCRIPT>
document.write("1");
document.write("2");
for (i=1; i<=5; i++)
document.write("3");
document.write(i);
document.write("4");
document.write("5");
</SCRIPT>
EXAMPLE
<!DOCTYPE html>
<html>
<body>
<p id="demo"></p>
<script>
const dept = ["CSE", "CIVIL", "ECE", "EEE", "EIE", "MECHANICAL"];
document.getElementById("demo").innerHTML = text;
</script>
</body>
</html>
OBJECTS
• Objects have attributes and methods.
• Many pre-defined objects and object types.
• Using objects follows the syntax of C++/Java:
objectname.attributename
objectname.methodname()
document.writeln() Same as write(), but adds a newline character after each statement
User-defined Objects
All user-defined objects and built-in objects are descendants of an object called Object.
The new operator is used to create an instance of an object.
To create an object, the new operator is followed by the constructor method.
More Objects
The constructor methods are Object(), Array(), and Date() and String(). These constructors
are built-in JavaScript functions.
var employee = new Object();
var books = new Array("C++", "Perl", "Java");
var day = new Date("August 15, 1947");
Objects are variables too. But objects can contain many values.
The values are written as name : value pairs (name and value separated by a colon).
Object Definition
You define (and create) a JavaScript object with an object literal:
Example
var person = {firstName:"John", lastName:"Doe", age:50, eyeColor:"blue"};
Spaces and line breaks are not important. An object definition can span multiple lines:
var person = {
firstName: "John",
lastName: "Doe",
age: 50,
eyeColor: "blue"
};
EXAMPLE:
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Objects</h2>
<p id="demo"></p>
<script>
// Create an object:
var person = {firstName:"John", lastName:"Doe", age:50, eyeColor:"blue"};
// Display some data from the object:
document.getElementById("demo").innerHTML =
person.firstName + " is " + person.age + " years old.";
</script>
</body>
</html>
Object Properties
The name:values pairs in JavaScript objects are called properties:
(ii) objectName["propertyName"]
Eg: person["lastName"];
Object Methods
Objects can also have methods.
Methods are actions that can be performed on objects.
Methods are stored in properties as function definitions
Example: fullNamefunction() -- {return this.firstName + " " + this.lastName;}
A method is a function stored as a property.
var person = {
firstName: "John",
lastName : "Doe",
id : 5566,
fullName : function() {
return this.firstName + " " + this.lastName;
}
};
value.</p>
<p id="demo"></p>
<script>
// Create an object:
var person = {
firstName: "John",
lastName : "Doe",
id : 5566,
fullName : function() {
return this.firstName + " " + this.lastName;
}
};
// Display data from the object:
document.getElementById("demo").innerHTML = person.fullName();
</script>
</body>
</html>
JAVASCRIPT - DOCUMENT OBJECT MODEL OR DOM
Every web page resides inside a browser window which can be considered as an object.
A Document object represents the HTML document that is displayed in that window.
The way a document content is accessed and modified is called the Document Object
Model, or DOM.
The Objects are organized in a hierarchy.
Document object − Each HTML document that gets loaded into a window becomes a
document object.
Form control elements − All the elements such as text fields, buttons, radio buttons, and
checkboxes.
Common Methods and Properties
Finding HTML Elements
getElementById(): To access elements and attributes with id
innerHTML: To access the content of an element.
getElementsByTagName()
document.getElementsByClassName(name, value)
createElement: To create new element
removeChild: Remove an element
an event handler to a particular element like this:
document.getElementById(id).addEventListener("click", functionname)
Example:
<html>
<head> <title>DOM!!!</title></head>
<body>
<p>This is the welcome message.</p>
<p id="second">This is the technology section.</p>
<input type="button" id="btnClick" value="Click Me!!" />
<script type="text/javascript">
var paragraphs = document.getElementsByTagName("p");
alert("Content in the second paragraph is " + paragraphs[1].innerHTML);
document.getElementById("second").innerHTML = "The orginal message is changed.";
document.getElementById("btnClick").addEventListener("click", clicked);
function clicked() { alert("You clicked me!!!"); }
</script>
</body>
</html>
CHANGING HTML ELEMENTS
Method Description
element.setAttribute(attribute, value)
document.createElement(element)
document.removeChild(element)
document.appendChild(element)
document.replaceChild(element)
document.write(text)