Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
3 views

Unit_IV_JavaScript_New

The document provides an introduction to JavaScript, a lightweight, object-oriented programming language used for web development. It covers its features, applications, syntax, and various programming concepts such as variables, operators, control structures, and loops. Additionally, it includes examples of JavaScript code for practical understanding and implementation in web pages.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

Unit_IV_JavaScript_New

The document provides an introduction to JavaScript, a lightweight, object-oriented programming language used for web development. It covers its features, applications, syntax, and various programming concepts such as variables, operators, control structures, and loops. Additionally, it includes examples of JavaScript code for practical understanding and implementation in web pages.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 22

Introduction to Web Designing 1 (KIT-401)

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.

Why Use JavaScript?

 JavaScript enhances Web pages with dynamic and interactive features.


 JavaScript runs in client software.
 JavaScript 1.3 works with version 4.0 browsers.
What Can JavaScript Do?

 Common JavaScript tasks can replace server-side scripting.


 JavaScript enables shopping carts, form validation, calculations, special graphic and text
effects, image swapping, image mapping, clocks, and more.

JavaScript Syntax.

 Unlike HTML, JavaScript is case sensitive.


 Dot Syntax is used to combine terms.
◦ e.g., document.write("Hello World")
 Certain characters and terms are reserved.
 JavaScript is simple text (ASCII).

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>

<h2>Demo JavaScript in Head</h2>

<p id="demo">A Paragraph.</p>

<button type="button" onclick="myFunction()">Try it</button>

</body>
</html>
Output:

Demo JavaScript in Head


A Paragraph.

Try it

Prepared By: B.K. Saraswat, Asstt.Prof.


Introduction to Web Designing 3 (KIT-401)

JavaScript in <body>
In this example, a JavaScript function is placed in the <body> section of an HTML page.

<html>
<body>

<h2>Demo JavaScript in Body</h2>

<p id="demo">A Paragraph.</p>

<button type="button" onclick="myFunction()">Try it</button>

<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>

<h2>Demo External JavaScript</h2>

<p id="demo">A Paragraph.</p>

<button type="button" onclick="myFunction()">Try it</button>

<p>This example links to "myScript.js".</p>


<p>(myFunction is stored in "myScript.js")</p>

<script src="myScript.js"></script>

</body>
</html>

Prepared By: B.K. Saraswat, Asstt.Prof.


Introduction to Web Designing 4 (KIT-401)

JavaScript Display Possibilities


JavaScript can "display" data in different ways:
• Writing into an HTML element, using innerHTML.
• Writing into the HTML output using document.write().
• Writing into an alert box, using window.alert().
• Writing into the browser console, using console.log().
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:
<html>
<body>

<h1>My First Web Page</h1>


<p>My First Paragraph</p>

<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>

<h2>My First Web Page</h2>


<p>My first paragraph.</p>

<p>Never call document.write after the document has finished loading.


It will overwrite the whole document.</p>

<script>
document.write(5 + 6);
</script>

</body>
</html>

Prepared By: B.K. Saraswat, Asstt.Prof.


Introduction to Web Designing 5 (KIT-401)

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>

Prepared By: B.K. Saraswat, Asstt.Prof.


Introduction to Web Designing 6 (KIT-401)
<button onclick="window.print()">Print this page</button>
</body>
</html>

Output:
The window.print() Method

Click the button to print the current page.


Print this page

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>

Prepared By: B.K. Saraswat, Asstt.Prof.


Introduction to Web Designing 7 (KIT-401)
<script>
let x = 5;
let y = 6;
let z = x + y;
document.write(z);
</script>
When to Use JavaScript var?
Always declare JavaScript variables with var,let, orconst.
The var keyword is used in all JavaScript code from 1995 to 2015.
The let and const keywords were added to JavaScript in 2015.
If you want your code to run in older browser, you must use var.
JavaScript Let
The let keyword was introduced in ES6 (2015).
Variables defined with let cannot be Redeclared.
Variables defined with let must be Declared before use.
Variables defined with let have Block Scope.
Example
let x = "John Doe";

let x = 0;

// SyntaxError: 'x' has already been declared

Note: -With var you can:

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:

Prepared By: B.K. Saraswat, Asstt.Prof.


Introduction to Web Designing 8 (KIT-401)

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 using the var keyword can impose problems.

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

The const keyword was introduced in ES6 (2015).

Variables defined with const cannot be Redeclared.

Variables defined with const cannot be Reassigned.

Variables defined with const have Block Scope.

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;

When to use JavaScript const?


As a general rule, always declare a variable with const unless you know that the value will change.
Use const when you declare:
• A new Array
• A new Object
• A new Function
• A new RegExp
Constant Arrays
You can change the elements of a constant array:
<p id="demo"></p>
<script>
// Create an Array:
const cars = ["Saab", "Volvo", "BMW"];

// 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:

Prepared By: B.K. Saraswat, Asstt.Prof.


Introduction to Web Designing 11 (KIT-401)
<script>
var data=200;//gloabal variable
function a(){
document.writeln(data);
}
function b(){
document.writeln(data);
}
a();//calling JavaScript function
b();
</script>

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.

There are following types of operators in JavaScript.


1. Arithmetic Operators
2. Comparison (Relational) Operators
3. Bitwise Operators
4. Logical Operators
5. Assignment Operators
6. Special Operators

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

It evaluates the content only if expression is true.

Prepared By: B.K. Saraswat, Asstt.Prof.


Introduction to Web Designing 12 (KIT-401)
if(expression){

//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

It evaluates the content whether condition is true of false.

if(expression){
//content to be evaluated if condition is true
}
else{
//content to be evaluated if condition is false
}

Prepared By: B.K. Saraswat, Asstt.Prof.


Introduction to Web Designing 13 (KIT-401)

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

Prepared By: B.K. Saraswat, Asstt.Prof.


Introduction to Web Designing 14 (KIT-401)
}
else{
//content to be evaluated if no expression is true
}
Example:
<script>
var a=20;
if(a==10){
document.write("a is equal to 10");
}
else if(a==15){
document.write("a is equal to 15");
}
else if(a==20){
document.write("a is equal to 20");
}
else{
document.write("a is not equal to 10, 15 or 20");
}
</script>

JavaScript Loops

There are four types of loops in JavaScript.

1. for loop
2. while loop
3. do-while loop
4. for-in loop

1) JavaScript For 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>

3) JavaScript do while loop

Syntax:-
do{
code to be executed
} while (condition);
Example:
<script>
var i=21;
do{
document.write(i + "<br/>");

Prepared By: B.K. Saraswat, Asstt.Prof.


Introduction to Web Designing 16 (KIT-401)
i++;
}while (i<=25);
</script>
4) JavaScript for in loop

The JavaScript for in loop is used to iterate the properties of an object.

JavaScript Terminology

 JavaScript programming uses specialized terminology.


 Understanding JavaScript terms is fundamental to understanding the script.
 Objects, Properties, Methods, Events, Functions, Values, Variables, Expressions, Operators.

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();

Prepared By: B.K. Saraswat, Asstt.Prof.


Introduction to Web Designing 17 (KIT-401)
document.getElementById("demo").innerHTML = d;
</script>
<html>
<body>
<p id="demo"></p>
<script>
var d = new Date();
document.getElementById("demo").innerHTML = d.toString();
</script>
</body>
</html>
Thu Feb 16 2017 23:48:14 GMT+0530 (India Standard Time)

<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

 Properties are object attributes.


 Object properties are defined by using the object's name, a period, and the property name.
◦ e.g., background color is expressed by: document.bgcolor .
◦ documentis the object.
◦ bgcoloris the property.
Methods
 Methods are actions applied to particular objects. Methods are what objects can do.

Prepared By: B.K. Saraswat, Asstt.Prof.


Introduction to Web Designing 18 (KIT-401)

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:

Event Performed Event Handler Description

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

mousemove onmousemove When the mouse movement takes place.

Keyboard events:
Event Performed Event Handler Description

Keydown & Keyup onkeydown & onkeyup When the user press and then release the key

Prepared By: B.K. Saraswat, Asstt.Prof.


Introduction to Web Designing 19 (KIT-401)

Form events:

Event Event Description


Performed Handler

focus onfocus When the user focuses on an element

submit onsubmit When the user submits the form

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

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.

Advantage of JavaScript function

There are mainly two advantages of JavaScript functions.

 Code reusability: We can call a function several times so it save coding.


 Less coding: It makes our program compact. We don’t need to write many lines of code
each time to perform a common task.

JavaScript Function Syntax

The syntax of declaring function is given below.

function functionName([arg1, arg2, ...argN]){


//code to be executed
}
Example:-

<script>
function msg(){
alert("hello! this is message");
}
</script>
<input type="button" onclick="msg()" value="call function"/>

Prepared By: B.K. Saraswat, Asstt.Prof.


Introduction to Web Designing 22 (KIT-401)

JavaScript Function Arguments


<script>
function getcube(number){
alert(number*number*number);
}
</script>
<form>
<input type="button" value="click" onclick="getcube(4)"/>
</form>

Function with Return Value


<script>
function getInfo(){
return "hello javatpoint! How r u?";
}
</script>
<script>
document.write(getInfo());
</script>

JavaScript Function Object Examples


<script>
var add=new Function("num1","num2","return num1+num2");
document.writeln(add(2,5));
</script>

Expressions

 Expressions are commands that assign values to variables.


 Expressions always use an assignment operator, such as the equals sign.
◦ e.g., var month = May; is an expression.
 Expressions end with a semicolon.

Prepared By: B.K. Saraswat, Asstt.Prof.

You might also like