0% found this document useful (0 votes)
24 views87 pages

Jscript 1 1

Uploaded by

ranjith
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
24 views87 pages

Jscript 1 1

Uploaded by

ranjith
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 87

JAVA SCRIPT

• JavaScript is a programming language for use


in HTML pages
• JavaScript is a client-side scripting
language.
• JavaScript is used mainly for enhancing the
interaction of a user with the webpage.
• JavaScript allows you to add interactivity to a
web page.
JAVA SCRIPT
• It is often used with HTML and CSS to
enhance the functionality of a web page such
as validating forms, creating interactive maps,
and displaying animated charts.
• It is a light-weighted and interpreted language.
• It is a case-sensitive language.
• Open and cross-platform
JAVA SCRIPT
• JavaScript programs are run by an interpreter
built into the user's web browser

JavaScript can dynamically modify an HTML

page

• It can be used to validate user inputs, react to


user input
JAVA SCRIPT
JavaScript is a multi-paradigm language that
supports event-driven, functional, and
imperative (including object-oriented and
prototype-based) programming styles.
JavaScript was initially used only for the client-
side.
However, these days, JavaScript is used as a
server-side programming language as well.
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>
Where to Put your Scripts
• Scripts can be placed in the HEAD or in the BODY

In the HEAD, scripts are run before the page is
displayed –
In the BODY, scripts are run as the page is
displayed
• In the HEAD is the right place to define functions
and variables that are used by scripts within the
BODY
JAVA SCRIPT IN HTML

1) <html> 2) <html>

<head> <head>
<title>Hello JavaScript</title> <title>Hello JavaScript</title>
</head>
<script type="text/javascript“ >
document.write("Hello World!"); <body>
</script> <script type="text/javascript“ >
document.write("Hello World!");
</head> </script>
</body>
<body>
</body> </html>
</html>
JAVA SCRIPT IN HTML
• Write java script in a separate file with .js
extension.
• Include the external javascript file (.js) in HTML
as follows
<html>
<head>
<script type=“text/javascript” src=“hello.js”>
</script>
</head>
<body>
</body>
</html>
JAVA SCRIPT-Variables
Used to store information
Variable name are case sensitive
•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
•Can be declared with var or let or const
JAVA SCRIPT-Variables
// declaring single variable
var name;

// declaring multiple variables


var name, title, num;

// initializng variables
var name = "Harsh";
name = "Rakesh";
JAVA SCRIPT-Variables
// creating variable to store a number
var num = 5;
// store string in the variable num
num = "GeeksforGeeks";
// storing a mathematical expression
var x = 5 + 10 + 1;
console.log(x); // 16
JAVA SCRIPT-Variables
// let variable
let x; // undefined

let name = ‘john';


// can also declare multiple vlaues
let a=1,b=2,c=3;
// assignment
let a = 3; a = 4; // works same as var.
JAVA SCRIPT-Variables
let gives you the privilege to declare variables that
are limited in scope to the block, statement of
expression unlike var.

let variables are usually used when there is a limited


use of those variables.

Say, in for loops, while loops or inside the scope of if


conditions etc. Basically, where ever the scope of the
variable has to be limited.
JAVA SCRIPT-Variables

var x = 1;
if (x == 1)
{
let x = 2;
document.write(x); // expected output: 2
}
document.write(x);// expected output: 1
JAVA SCRIPT-Variables
The var statement declares a function-scoped or
globally-scoped variable, optionally initializing it
to a value.
var x = 1;
if (x == 1)
{
var x = 9;
document.write(x); // expected output: 9
}
document.write(x);// expected output: 9
JAVA SCRIPT-Variables Scope
• The scope of a variable is the region of your program in
which it is defined.
• JavaScript variables have only two scopes.

• Global Variables − A global variable has global scope


which means it can be defined anywhere in your
JavaScript code.
• Local Variables − A local variable will be visible only
within a function where it is defined. Function parameters
are always local to that function
JAVA SCRIPT-Variables Scope
var myVar = "global"; // a global variable
function checkscope( )
{
var myVar = "local"; // a local variable
document.write(myVar);
}
checkscope();
document.write(myVar);
JavaScript Operators
Data Types in JavaScript
• primitive (or primary)-
• String, Number, and Boolean ,Undefined, Null

• non primitive (or reference)-


Object, Array, and Function
Data Types in JavaScript
String type
•var a = "Let's have a cup of coffee.";
•var b = 'He said "Hello" and left.';
Number type
•var a = 25; // integer
•var b = 80.5; // floating-point number
•var c = 4.25e+6;
Data Types in JavaScript
Boolean type
•var a =true;
•var b =false;
Undefined type
•var a ;// undefined
Null type
•var c = null;
Object Data Type
• The object is a complex data type that allows you to store
collections of data.
• An object contains properties, defined as a key-value pair.
• A property key (name) is always a string, but the value can be
any data type, like strings, numbers, booleans, or complex data
types like arrays, function and other objects.

Example : var emptyObject = { };


var person = {
"name": "Clark",
"surname": "Kent",
"age": 36};
Array Data Type
• An array is a type of object used for storing multiple
values in single variable.
• Each value (also called an element) in an array has a
numeric position, known as its index
• It may contain data of any data type-numbers, strings,
booleans, functions, objects, and even other arrays .
• var colors = ["Red", "Yellow", "Green", "Orange"];
• var cities = ["London", "Paris", "New York"];
• alert(colors[0]);
• alert(cities[2]);
Array Data Type
• var arrayName = new Array();
• var arrayName = new Array(Number length);
• var arrayName = new Array(element1, element2,... elementN);
Array Methods
• concat() — Join several arrays into one
• indexOf() — Returns the primitive value of
the specified object
• join() — Combine elements of an array into a
single string and return the string
Array Methods
lastIndexOf() — Gives the last position at which a given
element appears in an array
pop() — Removes the last element of an array
push() — Add a new element at the end reverse() —
Sort elements in descending order
Functions in java script
• Creating functions
• function func_name(param1,param2…)
• {
• }
• Calling functions
• func_name();
• Functions with return values
Functions in java script
alert() –function
alert() — Output data in an alert box in the browser
window.
An alert dialog box is mostly used to give a warning
message to the users.
<head>
<script type="text/javascript">
<!--
alert("Warning Message");
//-->
</script>
</head>
Functions in java script
confirm() –function
confirm() — A confirmation dialog box is mostly used to
take user's consent on any option.
It displays a dialog box with two buttons: OK and Cancel.
<script language="javascript">
function respond()
{
var retVal = confirm("are u sure to continue");
if(retVal == true)
{
window.location="../first.html";
}
else{ alert("you have canceled the redirection"); }
}
</script>
Functions in java script
prompt() –function
Creates an dialogue for user input
Prompt function is often used to take the input from user

<head>
<script type="text/javascript">

var retVal = prompt(“someText", “defaultvalue");


alert("You have entered : " + retVal );

</script>
</head>
Functions in Javascript
• isFinite() — Determines whether a passed value is a
finite number
• isNaN() — Determines whether a value is Not a
Number or not .
• parseFloat() — Parses an argument and returns a
floating point number
• parseInt() — Parses its argument and returns an
integer
Objects in JavaScript

• Array object
• String object
• Math object
• Date object
Array Object
An array is a special variable, which can hold more than one
value, at a time.
An array can be defined in three ways.
The following code creates an Array object called myCars:
1: var myCars=new Array(); // regular array
myCars[0]="Saab";
myCars[1]="Volvo";
myCars[2]="BMW";

2: var myCars=new Array("Saab","Volvo","BMW");


3: var myCars=["Saab","Volvo","BMW"];
Array Object
Accessing an array
var myCars=["Saab","Volvo","BMW"];
document. write(myCars[0]);
output: Saab

Modify Values in an Array


To modify a value in an existing array, just add a new
value to the array with a specified index number:
• myCars[0]="Opel";
• document.write(myCars[0]);
• output: Opel
Array Object
Predefined Methods

1.length- It is the property that returns the length of the


given array.
Syntax: Array.length

var parents = ["Jani", "Tove"];


document.write(parents.length);
output : 2
Array Object
Predefined Methods
2. toString() :This method helps to convert the given
value into the string.
arr.toString()

let arr = ["Geeks", "for", "Geeks"];


let str = arr.toString();
console.log(str);
Array Object
Predefined Methods
join()-- This method helps to join two arrays as a string.
If we pass any parameter to this method it will join the array
by using that parameter.

Syntax: array.join(separator)
Example:
var fruits = ["Orange", "Apple", "Mango"];
document.write(fruits.join() + "<br />");
document.write(fruits.join("+") + "<br />");
document.write(fruits.join(" and "));
Array-predefined methods
concat():
The concat() method is used to concatenate the two
arrays and it gives the merged array.

var num1 = [11, 12, 13],


num2 = [14, 15, 16],
num3 = [17, 18, 19];

document.write(num1.concat(num2, num3));
Array-predefined methods
push(): Adding Element at the end of an Array
Array.push(item1, item2 …)
var number_arr = [10, 20, 30, 40, 50];
number_arr.push(60);

unshift(): This method is used to add elements to the front of


an Array.
Array.unshift(item1, item2 …)
var string_arr = ["amit", "sumit"];
string_arr.unshift("sunil", "anil");
Array-predefined methods
pop(): This method is used to remove elements from the end of
an array.
syntax: Array.pop()
var number_arr = [20, 30, 40, 50];
number_arr.pop();

shift(): This method is used to remove elements from the


beginning of an array
Array.shift()

var string_arr = ["amit", "sumit“,”sunil”];


string_arr.shift();
Array-predefined methods
splice(): This method is used for the Insertion and Removal of
elements in between an Array

Syntax: Array.splice (start, deleteCount, item 1, item 2….)

var number_arr = [20, 30, 40, 50, 60];

number_arr.splice(1, 3);

number_arr.splice(1, 0, 3, 4, 5);
Array-predefined methods
reverse() : The reverse() method reverses the elements in an
array.

var fruits = ["Orange", "Apple", "Mango"];


document.write(fruits.reverse());

sort(): The sort() method sorts an array alphabetically:

var fruits = ["Orange", "Apple", "Mango"];


document.write(fruits.sort());
String Object
• JavaScript strings are primitive values,
created from literals:
• var firstName = “javascript";
• Strings can also be defined as objects with
the keyword new:
• var firstName = new
String(“javascript");
String Object
Syntax:
var txt = new String(string);
or more simply:
var txt = string;

•var x = "John";
var y = new String("John");
String Object
• Length property
• length property returns the length of a string:

<script type="text/JavaScript">
var txt = "Hello World!";
document.write(txt.length);
</script>;
String Object-Methods
String Object-Methods
• charCodeAt():Returns the Unicode of the
character at the specified index
• Return the Unicode of the first character in a
string:
<script type="text/javascript">
var str = "Hello world!";
document.write("First character: " +
str.charCodeAt(0) + "<br />");
</script>
String Object-Methods
String Object-Methods
String Object-Methods
String Object-Methods
String Object-Methods
String Object-Methods
Math Object
Math Object
• abs(x) :Returns the absolute value of x

<script type="text/javascript">
document.write(Math.abs(7.25) + "<br />"); // 7.25
document.write(Math.abs(-7.25) + "<br />"); // 7.25
document.write(Math.abs(null) + "<br />"); // 0
document.write(Math.abs("Hello") + "<br />"); // NaN
document.write(Math.abs(2+3)); //5
</script>
Math Object
• ceil(x):Returns x, rounded upwards to the
nearest integer

• document.write(Math.ceil(0.60) + "<br />");


• document.write(Math.ceil(0.40) + "<br />");
Math Object
• floor(x):Returns x, rounded downwards to
the nearest integer
• document.write(Math.floor(0.60) + "<br />");
• document.write(Math.floor(0.40) + "<br />");

• max(x,y,z,...,n): Returns the number with the highest value


• min(x,y,z,...,n): Returns the number with the lowest value

• Pow(x,y):Returns the value of x to the power of y


• document.write(Math.pow(7,2) + "<br />");
• document.write(Math.pow(-7,2) + "<br />");
Math Object
Math Object
Math Object
Date Object
Date Object
EVENTS
• JavaScript's interaction with HTML is handled through events that occur when
the user or the browser manipulates a page .

Event is an action or occurrence detected by a program.


• The user clicking the mouse over a certain element or hovering the cursor over a
certain element.
• The user pressing a key on the keyboard.
• The user resizing or closing the browser window.
• A web page finishing loading.
• A form being submitted.
EVENTS
• JavaScript lets you execute code when
events are detected.

• HTML allows event handler attributes,


with JavaScript code, to be added to
HTML elements
EVENTS
• Mouse events:
• click – when the mouse clicks on an element
(touchscreen devices generate it on a tap).
• mouseover / mouseout – when the mouse cursor
comes over / leaves an element.
• mousedown / mouseup – when the mouse button is
pressed / released over an element.
• mousemove – when the mouse is moved.
EVENTS
Form element events:
•submit – when the visitor submits a <form>.
•focus – when the visitor focuses on an element,
e.g. on an <input>.
Keyboard events:
•keydown and keyup – when the visitor presses
and then releases the button.
EVENT HANDLERS
• To react on events we can assign a
handler – a function that runs in case of an
event.

• Handlers are a way to run JavaScript code


in case of user actions.
EVENT HANDLERS
There are several ways to assign a handler.
•HTML-attribute
A handler can be set in HTML with an attribute named
on<event>.
Ex:
<input value="Click me" onclick="alert('Click!')" type="button">
EVENT HANDLERS
• DOM property
We can assign a handler using a DOM property on<event>.
For instance, elem.onclick:

<input id="elem" type="button" value="Click me">


<script>
elem.onclick = function()
{
alert('Thank you');
};
</script>
Document Object Model
• The DOM is a W3C (World Wide Web Consortium)
standard.
• The DOM defines a standard for accessing documents:
• "The W3C Document Object Model (DOM) is a
platform and language-neutral interface that allows
programs and scripts to dynamically access and
update the content, structure, and style of a document."
Document Object Model
• JavaScript can access all the elements in
a webpage making use of Document
Object Model (DOM).
• In fact, the web browser creates a DOM of
the webpage when the page is loaded.
• The DOM model is created as a tree of
objects like this:
DOM
• The Objects are organized in a hierarchy. This hierarchical
structure applies to the organization of objects in a Web
document
DOM
• 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.
DOM
• The HTML DOM can be accessed with JavaScript In the DOM,
all HTML elements are defined as objects.

• The programming interface is the properties and methods of


each object.
• A property is a value that you can get or set (like changing the
content of an HTML element)
• A method is an action you can do (like add or deleting an
HTML element).
DOM

You might also like