Iwd Unit 4

Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 45

JAVASCRIPT

UNIT 4

Shalini Shukla
JAVASCRIPT 
 JavaScript is a lightweight, interpreted programming language.
 It is designed for creating network-centric applications.

 It is complimentary to and integrated with Java. JavaScript is very


easy to implement because it is integrated with HTML.
 It is open and cross-platform.

 JavaScript is the world's most popular programming language.

 JavaScript is the programming language of the Web.

 JavaScript is easy to learn.

 JavaScript is most commonly used as a client side scripting


language.
 This means that JavaScript code is written into an HTML page.

 When a user requests an HTML page with JavaScript in it, the


script is sent to the browser and it's up to the browser to do
something with it.
DIFFERENCE BETWEEN JAVASCRIPT AND JAVA
JavaScript Java
Cannot live outside a Web page Can build stand-alone applications or live
in a Web page as an applet.

Doesn‘t need a compiler Requires a compiler

Knows all about your page Applets are dimly aware of your Web
page.

Untyped Strongly typed


Somewhat object-oriented Object-oriented
 There are no relationship between in java & java script.
 Java Script is a scripting language that
 always dependent in HTML language. It used to css
commands. It is mainly used to creating
 DHTML pages & validating the data. This is called client side
validations.
Why we Use JavaScript?
 Using HTML we can only design a web page but you can not
run any logic on web browser
 like addition of two numbers, check any condition, looping
statements (for, while), decision
 making statement (if-else) at client side. All these are not
possible using HTML So for perform
 all these task at client side you need to use JavaScript.
FEATURES OF JAVASCRIPT
PROS AND CONS OF JAVASCRIPT
Pros:
 Allows more dynamic HTML pages, even complete web
applications
Cons:
 Requires a JavaScript-enabled browser

 Requires a client who trusts the server enough to run the code
the server provides
 JavaScript has some protection in place but can still cause
security problems for clients
 Remember JavaScript was invented in 1995 and web
browsers have changed a lot since then
USING JAVASCRIPT IN YOUR HTML
 JavaScript can be inserted into documents by
using the SCRIPT tag
<html>
<head>
<title>Hello World in JavaScript</title>
</head>
<body>
<script type= "text/javascript">
document.write("Hello World!");
</script>
</body>
</html>
WAY OF USING JAVASCRIPT
There are three places to put the JavaScript code.
 Between the <body> </body> tag of html (Inline JavaScript)

 Between the <head> </head> tag of html (Internal JavaScript)

 In .js file (External JavaScript)

Inline JavaScript
 When java script was written within the html element using attributes
related to events of the element then it is called as inline java script.
 Example of Inline JavaScript

<html>
<body>
<input type="button" value="Click"
<script type= "text/javascript">
onclick="alert('Button Clicked')"/> <!.... Method called..>
</script>
</body>
</html>
INTERNAL JAVASCRIPT
When java script was written within the section using element then it is called as
internal java script.
Example of Internal JavaScript

<html>
<head>
<script>
function msg()
{
alert("Welcome in JavaScript"); <!... Internal js…>
}
</script>
</head>
<form>
<input type="button" value="Click" onclick="msg()"/>
</form>
</html>
EXTERNAL JAVASCRIPT
 Writing java script in a separate file with extension .js is
called as external java script.
 For adding the reference of an External JavaScript file to
your html page, use tag with src attribute as follows
 <script type="text/javascript" src="filename.js"/>

 Create a file with name functions.js and write the following


java script functions in it.

function msg()
{
alert("Welcome in JavaScript");
}
CREATE A HTML PAGE AND USE THE FILE FUNCTIONS.JS AS
FOLLOWS
<html>
<head>
<script type="text/javascript" src=" functions.js ">
</script>
</head>
<body>
<form>
<input type="button" value="click" onclick="msg()"/>
</form>
</body>
</html>
VARIABLE DECLARATION
 Java script did not provide any data types for declaring variables and a variable
in java script can store any type of value.
 Hence java script is loosely typed language. We can use a variable directly
without declaring it.
 Only var keyword are use before variable name to declare any variable.

Syntax
var x;
Types of Variable in JavaScript
 Local Variable

 Global Variable

Local Variable
 A variable which is declared inside block or function is called local variable. It
is accessible within the function or block only.
 Global Variable

 A 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. 
FIND SUM OF TWO NUMBER USING JAVASCRIPT
<!doctype html>
<html>
<head>
<script>
function add(){
var a,b,c;
a=Number(document.getElementById("first").value);
<!----This code is used for receive input value form input field by id----- >
b=Number(document.getElementById("second").value);
c= a + b;
document.getElementById("answer").value= c;
}
</script>
</head>
<body>
<input id="first">
<input id="second">
<button onclick="add()">Add</button>
<!---This code is used for call add function when button clicked ----- >
<input id="answer">
</body>
</html>
JS FUNCTION

 An important part of JavaScript is the ability to create new functions within <script> and </script>
tag. Declare a function in JavaScript using function keyword. The keyword function precedes the
name of the function.
 Syntax
function functionName(parameter or not)
{.........
.........}
Example of JavaScript using Function
<html>
<head>
<script>
function getname()
{name=prompt("Enter Your Name");
alert("Welcome Mr/Mrs " + name); }
</script>
</head>
<form>
<input type="button" value="Click" onclick="getname()"/>
</form>
</html>
JAVASCRIPT ARRAYS
 • JavaScript has arrays that are indexed starting at 0
<script type= "text/javascript">
var colors = new Array();
colors[0] = "red";
colors[1] = "green";
colors[2] = "blue";
colors[3] = "orange";
colors[4] = "magenta";
colors[5] = "cyan";
for (var i in colors) {
document.write("<div style=\"background-color:"
+ colors[i] + ";\">"
+ colors[i] + "</div>\n");
}
</script>
JAVASCRIPT DIALOG BOX
 All JavaScript dialog box is a predefined function which is used for to
perform different-different task. Some function are given below;
Alert()
 Alert function of java script is used to give an alert message to the user.

prompt()
 Prompt function of java script is used to get input from the user.

confirm()
 confirm function of java script is used to get confirmation from user
before executing some task.
ALERT FUNCTION EXAMPLE
<!doctype html>
<html>
<head>
<script>
function alertmsg()
{
alert("Alert function call");
}
</script>
</head>
<form>
<input type="button" value="Click Me“ onclick="alertmsg()"/>
</form>
</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. This hierarchical
structure applies to the organization of objects in a Web document.
 Window object − Top of the hierarchy. It is the outmost element
of the object hierarchy.
 Document object − Each HTML document that gets loaded into a
window becomes a document object. The document contains the
contents of the page.
 Form object − Everything enclosed in the <form>...</form>
tags sets the form object.
 Form control elements − The form object contains all the
elements defined for that object such as text fields, buttons,
radio buttons, and checkboxes.
Here is a simple hierarchy of a few important objects −
METHODS OF WINDOW OBJECT
Method Description

displays the alert box containing


alert()
message with ok button.

Displays the confirm dialog box


confirm() containing message with ok and cancel
button.

Displays a dialog box to get input from


prompt()
the user.
open() Opens the new window.

close() Closes the current window.

Performs action after specified time


setTimeout() like calling function, evaluating
expressions etc.
JAVASCRIPT AND THE DOM
 The Document Object Model (DOM) is a specification that
determines a mapping between programming language objects
and the elementsof an HTML document
 Not specific to JavaScript

HTML DOM Objects


Environment objects
– Window, Navigator, Screen, History, Location, Document
HTML objects
– Anchor, Area, Base, Body, Button, Event, Form, Frame,
Frameset, Iframe, Image, Checkbox, FileUpload, Hidden,
Password, Radio, Reset, Submit, Text, Link, Meta, Object,
Option, Select, Style, Table, TableCell, TableRow, TextArea
HTML DOM: DOCUMENT
 The Document object represents an HTML document and can
be used to access all documents in a page
A Document contains several collections
 – anchors, forms, images, links

Has several properties


 – body, cookie, domain, lastModified, referrer, title, URL

Has several useful methods


 getElementById, getElementsByName,

 getElementsByTagName, write, writeln, open, close


HTML DOM: DOCUMENT
 An instance of Document is already created for you, called
document function changeF() {
var cText = document.getElementById("c");
var fText = document.getElementById("f");
...
}
...
<input type= "text" id= "c" onchange= "changeC()">C
<input type= "text" id= "f" onchange= "changeF()">F
METHODS OF DOCUMENT OBJECT
The important methods of document object are as follows:

Method Description

write("string") writes the given string on the doucment.

writeln("string") writes the given string on the doucment with


newline character at the end.

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.
CHANGING HTML STYLE
To change the style of an HTML element, use this syntax:
document.getElementById(id).style.property = new style
<html>
<body>
<p id="p2">Hello World!</p>
<script>
document.getElementById("p2").style.color = "blue";
</script>
</body>
</html>

JAVASCRIPT FORM VALIDATION

 JavaScriptprovides facility to validate the form on the client-side so data processing will be faster
than server-side validation.

 Most of the web developers prefer JavaScript form validation.

 Through JavaScript, we can validate name, password, email, date, mobile numbers and more
fields.
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Validation</h2>
<p>Please input a number between 1 and 10:</p>
<input id="numb">
<button type="button" onclick="myFunction()">Submit</button>
<p id="demo"></p>
<script>
function myFunction() {
// Get the value of the input field with id="numb"
let x = document.getElementById("numb").value;
// If x is Not a Number or less than one or greater than 10
let text;
if (isNaN(x) || x < 1 || x > 10) {
text = "Input not valid";
} else {
text = "Input OK";
}
document.getElementById("demo").innerHTML = text;
}</script></body></html>
<script>
function validateform(){
var name=document.myform.name.value;
var password=document.myform.password.value;

if (name==null || name==""){
alert("Name can't be blank");
return false;
}else if(password.length<6){
alert("Password must be at least 6 characters long.");
return false;
}
}
</script>
<body>
<form name="myform" method="post" action="abc.jsp" onsubmit="return validateform()" >
Name: <input type="text" name="name"><br/>
Password: <input type="password" name="password"><br/>
<input type="submit" value="register">
</form>
STATEMENTS AND DECLARATIONS
 JavaScript applications consist of statements with an appropriate syntax. A single
statement may span multiple lines. Multiple statements may occur on a single line if
each statement is separated by a semicolon. This isn't a keyword, but a group of
keywords.
Statements and declarations by category
Control flow
 Block A block statement is used to group zero or more statements. The block is
delimited by a pair of curly brackets.
 Break Terminates the current loop, switch, or label statement and transfers program
control to the statement following the terminated statement.
 continue Terminates execution of the statements in the current iteration of the
current or labeled loop, and continues execution of the loop with the next iteration.
 Empty An empty statement is used to provide no statement, although the JavaScript
syntax would expect one.
 if...else Executes a statement if a specified condition is true. If the condition is false,
another statement can be executed.
 switch Evaluates an expression, matching the expression's value to a case clause,
and executes statements associated with that case.
 throw Throws a user-defined exception.
 try...catch Marks a block of statements to try, and specifies a response, should an
exception be thrown.
DECLARATIONS
 var Declares a variable, optionally initializing it to a value.
 let Declares a block scope local variable, optionally
initializing it to a value.
 const Declares a read-only named constant.

Functions and classes


 function Declares a function with the specified parameters.

 function* Generator Functions enable writing iterators more


easily.
 async function Declares an async function with the specified
parameters.
 return Specifies the value to be returned by a function.

 class Declares a class.


ITERATIONS

 do...while Creates a loop that executes a specified statement


until the test condition evaluates to false. The condition is
evaluated after executing the statement, resulting in the
specified statement executing at least once.
 for Creates a loop that consists of three optional expressions,
enclosed in parentheses and separated by semicolons,
followed by a statement executed in the loop.
 whileCreates a loop that executes a specified statement as
long as the test condition evaluates to true. The condition is
evaluated before executing the statement.
CREATING OBJECTS IN JAVASCRIPT
There are 3 ways to create objects.
 By object literal
 By creating instance of Object directly (using new keyword)

 By using an object constructor (using new keyword)

1) JavaScript Object by object literal


 The syntax of creating object using object literal is given below:

object={property1:value1,property2:value2.....propertyN:valueN} 
 

<script>  
emp={id:102,name:"Shyam Kumar",salary:40000}  
document.write(emp.id+" "+emp.name+" "+emp.salary);  
</script>  
2) BY CREATING INSTANCE OF OBJECT

The syntax of creating object directly is given below:


var objectname=new Object();  

<script>  
var emp=new Object();  
emp.id=101;  
emp.name="Ravi Malik";  
emp.salary=50000;  
document.write(emp.id+" "+emp.name+" "+emp.salary);  
</script>  
3) BY USING AN OBJECT CONSTRUCTOR
 Here, you need to create function with arguments.
 Each argument value can be assigned in the current object by using this
keyword.
 The this keyword refers to the current object.

<script>  
function emp ( id, name , salary){  
this.id=id;  
this.name=name;  
this.salary=salary;  
}  
var e=new emp(103,"Vimal Jaiswal",30000);  
  
document.write(e.id+" "+e.name+" "+e.salary);  
</script>  
JAVASCRIPT EVENTS
 HTML events are "things" that happen to HTML elements.
 When JavaScript is used in HTML pages, JavaScript
can "react" on these events.
 For example, when a user clicks over the browser, add js
code, which will execute the task to be performed on the
event.

Some of the HTML events and their event handlers are:


 An HTML web page has finished loading

 An HTML input field was changed

 An HTML button was clicked


 Often, when events happen, you may want to do something.

 JavaScript lets you execute code when events are detected.

 HTML allows event handler attributes, with JavaScript code, to be added


to HTML elements.

With single quotes:


 <element event='some JavaScript'>

With double quotes:


 <element event="some JavaScript">

 Example
 <button onclick="document.getElementById('demo').innerHTML =
Date()">The time is?</button>
COMMON HTML EVENTS

Event Description
onchange An HTML element has been changed
onclick The user clicks an HTML element
onmouseover The user moves the mouse over an HTML element

onmouseout The user moves the mouse away from an HTML


element
onkeydown The user pushes a keyboard key
onload The browser has finished loading the page
JAVASCRIPT EVENT HANDLERS
Event handlers can be used to handle and verify user input, user
actions, and browser actions:
 Things that should be done every time a page loads
 Things that should be done when the page is closed
 Action that should be performed when a user clicks a button
 Content that should be verified when a user inputs data

Many different methods can be used to let JavaScript work with


events:
 HTML event attributes can execute JavaScript code directly
 HTML event attributes can call JavaScript functions
 You can assign your own event handler functions to HTML
elements
 You can prevent events from being sent or being handled
The <button> element should do something when someone
clicks on it.
 <button onclick="alert('Hello')">Click me.</button>

When the button is clicked, the function "myFunction" should


be executed.
 <button onclick="myFunction()">Click me.</button>

Keyboard events:
Key down & Key up
onkeydown & onkeyup events When the user press and then
release the key
FORM EVENTS:

Event Performed Event Description


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 Handler Description
Performed

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
JAVASCRIPT ARRAY
 JavaScript array is an object that represents a collection of similar type
of elements.
An JavaScript array has the following characteristics:
 First, an array can hold values of different types. For example, you can
have an array that stores the number and string, and boolean values.
 Second, the length of an array is dynamically sized and auto-growing.
In other words, you don’t need to specify the array size upfront.

There are 3 ways to construct array in JavaScript


 By array literal
 By creating instance of Array directly (using new keyword)
 By using an Array constructor (using new keyword)

1) JavaScript array literal


 The syntax of creating array using array literal is given
below:var arrayname=[value1,value2.....valueN];  
<script>  
var emp=["Sonoo","Vimal","Ratan"];  
for (i=0;i<emp.length;i++){  
document.write(emp[i] + "<br/>");  
}  
</script>  
2) JavaScript Array directly (new keyword)
 The syntax of creating array directly is given below:
 var arrayname=new Array();  
 Here, new keyword is used to create instance of array.
<script>  
var i;  
var emp = new Array();  
emp[0] = "Arun";  
emp[1] = "Varun";  
emp[2] = "John";   
for (i=0;i<emp.length;i++){  
document.write(emp[i] + "<br>");  
}  </script>  
3) JAVASCRIPT ARRAY CONSTRUCTOR (NEW
KEYWORD)
 Here, you need to create instance of array by passing
arguments in constructor so that we don't have to provide
value explicitly.

 The example of creating object by array constructor is


given below.
<script>  
var emp=new Array("Jai","Vijay","Smith");  
for (i=0;i<emp.length;i++){  
document.write(emp[i] + "<br>");  
}  
</script>  
JAVASCRIPT ARRAY METHODS

concat() It returns a new array object that contains two or more merged arrays.

find() It returns the value of the first element in the given array that satisfies the
specified condition.
findIndex() It returns the index value of the first element in the given array that
satisfies the specified condition.
indexOf() It searches the specified element in the given array and returns the index
of the first match.
pop() It removes and returns the last element of an array.

push() It adds one or more elements to the end of an array.

reverse() It reverses the elements of given array.

shift() It removes and returns the first element of an array.

slice() It returns a new array containing the copy of the part of the given array.

sort() It returns the element of the given array in a sorted order.


SUMMARIZATION OF JS ARRAYS

 In JavaScript, an array is an order list of values.

 Each value is called an element specified by an index.

 An array can hold values of mixed types.

 JavaScript arrays are dynamic. They grow or shrink as


needed.

You might also like