You are on page 1of 25

Unit V

JavaScript

• It was developed by Brendan Eich at Netscape in the year 1995.

• What is JavaScript?

JavaScript is a high level, interpreted, programming language used to make web pages
more interactive.

• It is used to create interactive websites. It is mainly used for:

• Client-side validation

• Dynamic drop-down menus

• Displaying date and time

• Build small but complete client side programs .

• Displaying popup windows and dialog boxes (like alert dialog box, confirm dialog box
and prompt dialog box)

• Displaying clocks etc.

Uses of JavaScript

• Client-side validation

• Dynamic drop-down menus

• Displaying date and time

• Validate user input in an HTML form before sending the data to a server.

• Build forms that respond to user input without accessing a server.

• Change the appearance of HTML documents and dynamically write HTML into separate
Windows.

• Open and close new windows or frames.

• Manipulate HTML "layers" including hiding, moving, and allowing the user to drag them
around a browser window.

• Build small but complete client side programs .


• Displaying popup windows and dialog boxes (like alert dialog box, confirm dialog box
and prompt dialog box)

• Displaying clocks etc.

Limitations of JavaScript

• Client-side JavaScript does not allow the reading or writing of files.

• It cannot be used for networking applications because there is no such support available.

• It doesn't have any multithreading or multiprocessor capabilities.

Feature of JavaScript

• JavaScript is a object-based scripting language.

• Giving the user more control over the browser.


• It Handling dates and time.

• It Detecting the user's browser and OS,

• It is light weighted.

• JavaScript is a scripting language and it is not java.

• JavaScript is interpreter based scripting language.

• JavaScript is case sensitive.

• JavaScript is object based language as it provides predefined objects.

• Every statement in javascript must be terminated with semicolon (;).

• Most of the javascript control statements syntax is same as syntax of control statements in
C language.

• An important part of JavaScript is the ability to create new functions within scripts.
Declare a function in JavaScript using function keyword.

JavaScript First Program

<!DOCTYPE HTML>

<html>

<body>

<script>

alert( 'Hello, world!' );

</script>

</body>

</html>

Variables and Keywords in JS

• JavaScript variables are containers for storing data values.

• In this example, x, y, and z, are variables, declared with the var keyword:
• var x = 5;
var y = 6;
var z = x + y;

• All JavaScript variables must be identified with unique names.

• These unique names are called identifiers.

• The general rules for constructing names for variable

• Names can contain letters, digits, underscores, and dollar signs.

• Names must begin with a letter

• Names can also begin with $ and _.

• Names are case sensitive (y and Y are different variables)

• Reserved words (like JavaScript keywords) cannot be used as names

s (unique identifiers) are:

JavaScript Function Scope

In JavaScript there are two types of scope:

• Local scope

• Global scope

Local JavaScript Variables

• Variables declared within a JavaScript function, become LOCAL to the function.

• Local variables have Function scope: They can only be accessed from within the
function.

• function myFunction() {
var carName = "Volvo";

// code here CAN use carName

Global JavaScript Variables


• A variable declared outside a function, becomes GLOBAL.

• A global variable has global scope: All scripts and functions on a web page can access it.

• var carName = "Volvo";

// code here can use carName

function myFunction() {

// code here can also use carName

JavaScript Data Types

Primitive Data Types

In JavaScript, there are six primitive data types:

• Boolean

• Number

• String

• Null

• Undefined

• Symbol

Boolean Data Type

A boolean data type represents only one of two values either true or false.

Example:

var boo1 = true;

var boo2 = false;

Number Data Type

• There is only one type of Number in JavaScript.


• Numbers can be written with or without a decimal point.

• A number can also be +Infinity, -Infinity, and NaN (not a number).

Example:

var num1 = 32;

var num2 = +Infinity;

String Data Type

• Strings are used for storing text. Strings must be inside of either double or single quotes.

• In JavaScript, Strings are immutable (they cannot be changed).

Example:

var str1 = 'hello, it is me';

var str2 = "hello, it's me";

Null & Undefined Data Types

Null Data Type:

• Null has one value - null.

• It is explicitly nothing.

Example:

var nothing = null;

Undefined Data Type:

• A variable that has no value is undefined.

Example:

var testVar;

console.log(testVar); // undefined

Null Data Type:

• Null has one value - null.

• It is explicitly nothing.
Example:

var nothing = null;

Undefined Data Type:

• A variable that has no value is undefined.

Example:

var testVar;

console.log(testVar); // undefined

Non-primitive Data Type

• Object

• Date

• Array

JavaScript Arithmetic Operators

Arithmetic operators are used to perform arithmetic on numbers:

Operator Description

+ Addition

- Subtraction

* Multiplication

** Exponentiation
/ Division

% Modulus (Division Remainder)

++ Increment

-- Decrement

JavaScript Assignment Operators

Assignment operators assign values to JavaScript variables.

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
**= x **= y x = x ** y

e.g

var x = 10;
x += 5;

O/P:- 15

JavaScript String Operators

The + operator can also be used to add (concatenate) strings.

Example
var txt1 = "John";
var txt2 = "Doe";
var txt3 = txt1 + " " + txt2;

The result of txt3 will be:

John Doe

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

? ternary operator

JavaScript Logical Operators

Operator Description

&& logical and

|| logical or

! logical not

JavaScript Bitwise Operators

Bit operators work on 32 bits numbers.

Any numeric operand in the operation is converted into a 32 bit number. The result is converted
back to a JavaScript number.
Operator Description Example Same as Result Decimal

& AND 5&1 0101 & 0001 1


0001

| OR 5|1 0101 | 0001 0101 5

~ NOT ~5 ~0101 1010 10

^ XOR 5^1 0101 ^ 0100 4


0001

<< Zero fill left shift 5 << 1 0101 << 1 1010 10

>> Signed right shift 5 >> 1 0101 >> 1 0010 2

>>> Zero fill right shift 5 >>> 1 0101 >>> 1 0010 2

JavaScript Functions

• JavaScript a function allows user to define a block of code, give it a name and then
execute it as many times as user want.

• A function can be defined using “function” keyword and can be executed using ()
operator.

• A function can include one or more parameters. It is optional to specify function


parameter values while executing it.
• JavaScript is a loosely-typed language. A function parameter can hold value of any data
type.

• User can specify less or more arguments while calling function.

• All the functions can access arguments object by default instead of parameter names.

• A function can return a literal value or another function.

• A function can be assigned to a variable with different name.

• JavaScript allows you to create anonymous functions that must be assigned to a variable.

Function Syntax

//defining a function

function <function-name>()

// code to be executed

};

//calling a function

<function-name>();

Function Example

<html>

<body>

<script>

function MyMessage()

alert("Hello World!");

MyMessage();
</script>

</body>

</html>

Function With Parameters

<html>

<body>

<script>

function ShowMessage(firstName, lastName)

alert("Hello " + firstName + " " + lastName);

ShowMessage(“Narendra", “Modi");

ShowMessage("Bill", "Gates");

ShowMessage(100, 200);

</script>

</body>

</html>

Function With Parameters

<html>

<body>

<script>

function ShowMessage(firstName, lastName)

alert("Hello " + firstName + " " + lastName);


}

ShowMessage(“Narendra", “Modi", "Mr.");

ShowMessage("Bill");

ShowMessage();

</script>

</body>

</html>

Return Values

<html>

<body>

<script>

function addition(val1, val2)

return val1 + val2;

};

alert("sum="+addition(10,20));

</script>

</body>

</html>

event handlers (onclick, onsubmit etc.)

What is an Event ?

JavaScript's interaction with HTML is handled through events that occur when the user or the
browser manipulates a page.
When the page loads, it is called an event. When the user clicks a button, that click too is an
event. Other examples include events like pressing any key, closing a window, resizing a
window, etc.
Developers can use these events to execute JavaScript coded responses, which cause buttons to
close windows, messages to be displayed to users, data to be validated, and virtually any other
type of response imaginable.
Events are a part of the Document Object Model (DOM) Level 3 and every HTML element
contains a set of events which can trigger JavaScript Code.

onclick Event Type

This is the most frequently used event type which occurs when a user clicks the left button of
his mouse. You can put your validation, warning etc., against this event type.

Example

Try the following example.


<html>
<head>
<script type = "text/javascript">
<!--
function sayHello() {
alert("Hello World")
}
//-->
</script>
</head>

<body>
<p>Click the following button and see result</p>
<form>
<input type = "button" onclick = "sayHello()" value = "Say Hello" />
</form>
</body>
</html>

onsubmit Event Type

onsubmit is an event that occurs when you try to submit a form. You can put your form
validation against this event type.

Example
The following example shows how to use onsubmit. Here we are calling a validate() function
before submitting a form data to the webserver. If validate() function returns true, the form will
be submitted, otherwise it will not submit the data.
Try the following example.
<html>
<head>
<script type = "text/javascript">
<!--
function validation() {
alert(“Good Morning”);
}
//-->
</script>
</head>

<body>
<form method = "POST" action = " " onsubmit = "return validation()">

<input type = "submit" value = "Submit" />


</form>
</body>
</html>

onmouseover and onmouseout

These two event types will help you create nice effects with images or even with text as well.
The onmouseover event triggers when you bring your mouse over any element and
the onmouseout triggers when you move your mouse out from that element. Try the following
example.

<html>
<head>
<script type = "text/javascript">
<!--
function over() {
document.write ("Mouse Over");
}
function out() {
document.write ("Mouse Out");
}
//-->
</script>
</head>

<body>
<p>Bring your mouse inside the division to see the result:</p>
<div onmouseover = "over()" onmouseout = "out()">
<h2> This is inside the division </h2>
</div>
</body>
</html>

Difference between client side scripting and server side scripting :


CLIENT SIDE

SCRIPTING SERVER SIDE SCRIPTING

Source code is not visible to user

Source code is visible to because it’s output

user. of server side is a HTML page.

In this any server side technology

It usually depends on can be use and it does not

browser and it’s version. depend on client.

It runs on user’s computer. It runs on web server.

The primary advantage is it’s

There are many advantages ability to highly customize,

link with this like faster. response

response times, a more requirements, access rights based

interactive application. on user.

It does not provide security

for data. It provides more security for data.


It is a technique use in web It is a technique that uses scripts on

development in which web server to produce a response

scripts runs on clients that is customized for each clients

browser. request.

HTML, CSS and javascript

are used. PHP, Python, Java, Ruby are used.

this keyword

• The JavaScript this keyword refers to the object it belongs to

• It has different values depending on where it is used:

• In a method, this refers to the owner object.

• Alone, this refers to the global object.

• In a function, this refers to the global object.

• In a function, in strict mode, this is undefined.

In an event, this refers to the element that received the event.

Example.

<script>

var website="Javatpoint";

function web()

document.write(this.website);

web();

</script>
<html>

<body>

<h1 onclick="this.innerHTML = 'Ooops!'">Click on this text!</h1>

<h2 onclick="this.innerHTML=' You are welcome'">Hello!</h2>

</body>

</html>

DOM(Document Object Model)

• With the HTML DOM, JavaScript can access and change all the elements of an HTML
document.

• With the object model, JavaScript gets all the power it needs to create dynamic HTML:

• JavaScript can change all the HTML elements in the page

• JavaScript can change all the HTML attributes in the page

• JavaScript can change all the CSS styles in the page

• JavaScript can remove existing HTML elements and attributes

• JavaScript can add new HTML elements and attributes

• JavaScript can react to all existing HTML events in the page

• JavaScript can create new HTML events in the page

• When a web page is loaded, the browser creates a Document Object Model of the page.

• The HTML DOM model is constructed as a tree of Objects:


The HTML DOM Document Object
The document object represents your web page.

If you want to access any element in an HTML page, you always start with accessing the
document object.

Below are some examples of how you can use the document object to access and manipulate
HTML.

Finding HTML Elements


Method Description

document.getElementById(id) Find an element by element


id

document.getElementsByTagName(name) Find elements by tag name

document.getElementsByClassName(name) Find elements by class


name

e.g1.

<html>

<body>

<h1 id="demo">This is section B</h1>

<script>

document.getElementById("demo").innerHTML="Good morning students";

</script>

</body>

</html>

e.g.2

<h1>This is a Heading</h1>

<h1>This is a Heading</h1>

<script>

document.getElementsByTagName("h1")[1].innerHTML = "Hello World!";

</script>

FORM Validation in Javascript

JavaScript Form Validation


HTML form validation can be done by JavaScript.

If a form field (fname) is empty, this function alerts a message, and returns false, to prevent the
form from being submitted:

Data Validation
Data validation is the process of ensuring that user input is clean, correct, and useful.

Typical validation tasks are:

• has the user filled in all required fields?


• has the user entered a valid date?
• has the user entered text in a numeric field?

Most often, the purpose of data validation is to ensure correct user input.

Validation can be defined by many different methods, and deployed in many different ways.

Server side validation is performed by a web server, after input has been sent to the server.

Client side validation is performed by a web browser, before input is sent to a web server.

e.g.

<html>

<body bgcolor="pink">

<form action="" method="" onsubmit="validation()" name="myform">

enter your name<input type="text" id="uname">

<br><br>

Password<input type="password" id="pwd">

<br><br>

Confirm Password<input type="password" id="cpwd">

<br><br>

Mobile Number<input type="text" id="mob">

<br><br>

Email Id<input type="text" id="email">

<br><br>

<input type="submit" value="next">


</form>

<script>

function validation(){

var name=document.getElementById('uname').value;

var pass=document.getElementById('pwd').value;

var cpass=document.getElementById('cpwd').value;

var mobile=document.getElementById('mob').value;

var email=document.getElementById('email').value;

if(name=="")

alert("enter ur name");

if((name.length < 8)||(name.length > 20)){

alert("enter the length must be between 8 and 20");

if(!isNaN(name))

alert("only characters are allowed");

if(pass=="")

alert("enter ur name");

if((pass.length < 6)||(pass.length > 20)){


alert("password length must be between 8 and 20");

if(cpass!=pass){

alert("password and confirm password are not same");

if(isNaN(mobile)){

alert("mobile number should be digit");

if(mobile.length!=10){

alert("mobile number should be of 10 digits");

if(email.indexOf('@')<=0){

alert("improper mail id");

else

alert("you good to go");

</script>

</body>

</html>

O/P:-

You might also like