Unit_IV_JavaScript_New
Unit_IV_JavaScript_New
Unit-IV
JAVASCRIPT
What is JavaScript?
JavaScript is a programming language designed for Web pages. JavaScript (js) is a light-weight
object-oriented programming language which is used by several websites for scripting the
webpages. It is an interpreted, full-fledged programming language that enables dynamic
interactivity on websites when applied to an HTML document.
Features of JavaScript
There are following features of JavaScript:
1. All popular web browsers support JavaScript as they provide built-in execution
environments.
2. JavaScript follows the syntax and structure of the C programming language. Thus, it is a
structured programming language.
3. JavaScript is a weakly typed language, where certain types are implicitly cast (depending
on the operation).
4. JavaScript is an object-oriented programming language that uses prototypes rather than
using classes for inheritance.
5. It is a light-weighted and interpreted language.
6. It is a case-sensitive language.
JavaScript Syntax.
Example: <script>
document. write ("Hello JavaScript by JavaScript");
</script>
Prepared By: B.K. Saraswat, Asstt.Prof.
Introduction to Web Designing 2 (KIT-401)
Application of JavaScript
JavaScript is used to create interactive websites. It is mainly used for:
o Client-side validation,
o Dynamic drop-down menus,
o Displaying date and time,
o Displaying pop-up windows and dialog boxes (like an alert dialog box, confirm dialog box
and prompt dialog box),
o Displaying clocks etc.
JavaScript in <head> or <body>
Scripts can be placed in the <body>, or in the <head> section of an HTML page, or in both.
JavaScript in <head>
In this example, a JavaScript function is placed in the <head> section of an HTML page.
The function is invoked (called) when a button is clicked:
<html>
<head>
<script>
function myFunction() {
document.getElementById("demo").innerHTML = "Paragraph changed.";
}
</script>
</head>
<body>
</body>
</html>
Output:
Try it
JavaScript in <body>
In this example, a JavaScript function is placed in the <body> section of an HTML page.
<html>
<body>
<script>
function myFunction() {
document.getElementById("demo").innerHTML = "Paragraph changed.";
}
</script>
</body>
</html>
External JavaScript:
External file: myScript.js
function myFunction()
{
document.getElementById("demo").innerHTML = "Paragraph changed.";
}
main.html
<html>
<body>
<script src="myScript.js"></script>
</body>
</html>
<p id="demo"></p>
<script>
document.getElementById("demo").innerHTML = 5 + 6;
</script>
</body>
</html>
Using document.write()
For testing purposes, it is convenient to use document.write():
<html>
<body>
<script>
document.write(5 + 6);
</script>
</body>
</html>
Using window.alert()
You can use an alert box to display data:
<html>
<body>
<h1>My First Web Page</h1>
<p>My first paragraph.</p>
<script>
window.alert(5 + 6);
</script>
</body>
</html>
You can skip the window keyword.
Using console.log()
For debugging purposes, you can call the console.log() method in the browser to display data.
<html>
<body>
<script>
console.log(5 + 6);
</script>
</body>
</html>
JavaScript Print
JavaScript does not have any print object or print methods.
You cannot access output devices from JavaScript.
The only exception is that you can call the window.print() method in the browser to print the
content of the current window.
<html>
<body>
<h2>The window.print() Method</h2>
<p>Click the button to print the current page.</p>
Output:
The window.print() Method
JavaScript Comments
Not all JavaScript statements are "executed".
Code after double slashes // or between /* and */ is treated as a comment.
Comments are ignored, and will not be executed:
JavaScript Variables
4 Ways to Declare a JavaScript Variable:
• Using var
• Using let
• Using const
• Using nothing
Example:
<script>
var x = 10;
var y = 20;
var z=x+y;
document.write(z);
Example:
</script>
let x = 0;
Example
var x = "John Doe";
var x = 0;
Block Scope
Before ES6 (2015), JavaScript had only Global Scope and Function Scope.
ES6 introduced two important new JavaScript keywords: let and const.
These two keywords provide Block Scope in JavaScript.
Variables declared inside a { } block cannot be accessed from outside the block:
Example
{
let x = 2;
}
// x can NOT be used here
Variables declared with the var keyword can NOT have block scope.
Variables declared inside a { } block can be accessed from outside the block.
Example
{
var x = 2;
}
// x CAN be used here
Redeclaring Variables
Redeclaring a variable inside a block will also redeclare the variable outside the block:
Example
var x = 10;
// Here x is 10
{
var x = 2;
// Here x is 2
}
// Here x is 2
Redeclaring a variable using the let keyword can solve this problem.
Redeclaring a variable inside a block will not redeclare the variable outside the block:
Example
let x = 10;
// Here x is 10
{
let x = 2;
// Here x is 2
}
// Here x is 10
Prepared By: B.K. Saraswat, Asstt.Prof.
Introduction to Web Designing 9 (KIT-401)
JavaScript Const
Example
const PI = 3.141592653589793;
PI = 3.14; // This will give an error
PI = PI + 10; // This will also give an error
Correct
const PI = 3.14159265359;
Incorrect
const PI;
PI = 3.14159265359;
// Change an element:
Prepared By: B.K. Saraswat, Asstt.Prof.
Introduction to Web Designing 10 (KIT-401)
cars[0] = "Toyota";
// Add an element:
cars.push("Audi");
// Display the Array:
document.getElementById("demo").innerHTML = cars;
</script>
Constant Objects
You can change the properties of a constant object:
<p id="demo"></p>
<script>
// Create an object:
const car = {type:"Fiat", model:"500", color:"white"};
// Change a property:
car.color = "red";
// Add a property:
car.owner = "Johnson";
// Display the property:
document.getElementById("demo").innerHTML = "Car owner is " + car.owner;
</script>
A JavaScript variable is simply a name of storage location. There are two types of variables in
JavaScript : local variable and global variable.
A JavaScript local variable is declared inside block or function. It is accessible within the function
or block only. For example:
<script>
function abc(){
var x=10;//local variable
}
</script>
A JavaScript global variable is accessible from any function. A variable i.e. declared outside the
function or declared with window object is known as global variable. For example:
JavaScript Operators
JavaScript operators are symbols that are used to perform operations on operands.
For example:
1. var sum=10+20;
Here, + is the arithmetic operator and = is the assignment operator.
JavaScript If-else
The JavaScript if-else statement is used to execute the code whether condition is true or false.
There are three forms of if statement in JavaScript.
1. If Statement
2. If else statement
3. if else if statement
JavaScript If statement
//content to be evaluated
<script>
var a=20;
if(a>10){
document.write("value of a is greater than 10");
}
</script>
JavaScript If...else Statement
if(expression){
//content to be evaluated if condition is true
}
else{
//content to be evaluated if condition is false
}
Example:
<script>
var a=20;
if(a%2==0){
document.write("a is even number");
}
else{
document.write("a is odd number");
}
</script>
JavaScript If...else if statement
It evaluates the content only if expression is true from several expressions.
if(expression1){
//content to be evaluated if expression1 is true
}
else if(expression2){
//content to be evaluated if expression2 is true
}
else if(expression3){
//content to be evaluated if expression3 is true
JavaScript Loops
1. for loop
2. while loop
3. do-while loop
4. for-in loop
The JavaScript for loop iterates the elements for the fixed number of times.
Syntax:-
for (initialization; condition; increment)
{
Prepared By: B.K. Saraswat, Asstt.Prof.
Introduction to Web Designing 15 (KIT-401)
code to be executed
}
Example:
<script>
for (i=1; i<=5; i++)
{
document.write(i + "<br/>")
}
</script>
2) JavaScript while loop
Syntax:-
while (condition)
{
code to be executed
}
Example:
<script>
var i=11;
while (i<=15)
{
document.write(i + "<br/>");
i++;
}
</script>
Syntax:-
do{
code to be executed
} while (condition);
Example:
<script>
var i=21;
do{
document.write(i + "<br/>");
JavaScript Terminology
Objects
An Object is a collection of properties and method which can be viewed, modified and interacted
with.
A simple example of property is color, which is rather easy to visualize.
They can be directly manipulated by referring to the object and the property by name and
then setting its value.
For example, the background color of a page can be changed as:
document.bgcolor=“blue”;
Html objects which belong to the DOM, have a descending relationship with each other.
The Topmost object in the DOM is Navigator itself.
The next level in the DOM is the brower’s Window.
The next level in the DOM is the Document displayed in the browser’s window.
JavaScript provides a few other object that are not related to the current window or the document
loaded in the current window. These objects are used quit extensively for data processing in
javaScript.
String Object
The Math Object
The Date Object
Date Object
The Date object is used to work with dates and times.
Date objects are created with new Date().
There are four ways of instantiating a date:
var d = new Date();
var d = new Date(milliseconds);
var d = new Date(dateString);
var d = new Date(year, month, day, hours, minutes, seconds, milliseconds);
<p id="demo"></p>
<script>
d = new Date();
<html>
<body>
<p id="demo"></p><script>
var d = new Date();
document.getElementById("demo").innerHTML = d.toDateString();
</script>
</body>
</html>
Thu Feb 16 2017
The window object represents the current browsing context. It holds things like window.location,
window.history, window.screen, window.status, or the window.document.
It has information about the framing setup (the frames, parent, top, self properties), and
holds important interfaces such as applicationCache, XMLHttpRequest, setTimeout, escape,
console or localStorage.
it acts as the global scope for JavaScript, i.e. all global variables are properties of it.
var local=88;
window.global2=99;
Document Object: represents the DOM that is currently loaded in the window - it's just a part of
it.
A document holds information like the documentElement (usually <html>), the forms
collection, the cookie string, its location, or its readyState.
It also implements a different interface (there might be multiple Documents, for example
an XML document obtained via ajax), with methods like getElementById or addEventListener.
Properties
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. When javascript code is
included in HTML, js react over these events and allow the execution. This process of reacting
over the events is called Event Handling. Thus, js handles the HTML events via Event Handlers.
For example, when a user clicks over the browser, add js code, which will execute the task to be performed
on the event.
Mouse events:
mouseover onmouseover When the cursor of the mouse comes over the 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 Performed Event Handler Description
Keydown & Keyup onkeydown & onkeyup When the user press and then release the key
Form events:
Window/Document events:
Event Event Description
Performed Handler
Load onload When the browser finishes the loading of the page
Unload onunload When the visitor leaves the current webpage, the browser
unloads it
Resize onresize When the visitor resizes the window of the browser
Click event:
<html>
<head> Javascript Events </head>
<body>
<script language="Javascript" type="text/Javascript">
<!--
function clickevent()
{
document.write("This is JavaTpoint");
}
//-->
Prepared By: B.K. Saraswat, Asstt.Prof.
Introduction to Web Designing 20 (KIT-401)
</script>
<form>
<input type="button" onclick="clickevent()" value="Who's this?"/>
</form>
</body>
</html>
MouseOver Event
<html>
<head>
<h1> Javascript Events </h1>
</head>
<body>
<script language="Javascript" type="text/Javascript">
<!--
function mouseoverevent()
{
alert("This is JavaTpoint");
}
//-->
</script>
<p onmouseover="mouseoverevent()"> Keep cursor over me</p>
</body>
</html>
Keydown Event
<html>
<head> Javascript Events</head>
<body>
<h2> Enter something here</h2>
<input type="text" id="input1" onkeydown="keydownevent()"/>
<script>
<!--
function keydownevent()
{
Prepared By: B.K. Saraswat, Asstt.Prof.
Introduction to Web Designing 21 (KIT-401)
document.getElementById("input1");
alert("Pressed a key");
}
//-->
</script>
</body>
</html>
Functions
Functions are named statements that performs tasks.
◦ e.g., function doWhatever () {statement here}
◦ The curly braces contain the statements of the function.
JavaScript has built-in functions, and you can write your own.
JavaScript functions are used to perform operations. We can call JavaScript function many times
to reuse the code.
<script>
function msg(){
alert("hello! this is message");
}
</script>
<input type="button" onclick="msg()" value="call function"/>
Expressions