0% found this document useful (0 votes)
2 views56 pages

Javascript

JavaScript is a lightweight, interpreted scripting language primarily used to add interactivity to HTML pages and validate data on the client side. It supports various web browsers and has a syntax similar to C, C++, and Java, making it easy to learn and implement. The document covers JavaScript's features, including data types, operators, control structures, functions, and the Document Object Model (DOM), along with practical examples and methods for embedding and using JavaScript in web development.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views56 pages

Javascript

JavaScript is a lightweight, interpreted scripting language primarily used to add interactivity to HTML pages and validate data on the client side. It supports various web browsers and has a syntax similar to C, C++, and Java, making it easy to learn and implement. The document covers JavaScript's features, including data types, operators, control structures, functions, and the Document Object Model (DOM), along with practical examples and methods for embedding and using JavaScript in web development.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 56

Javascript

By RIDDHI RANA
What is Javascript?
• JavaScript is a Scripting Language.
• It is a lightweight programming language.
• It is usually embedded directly into HTML pages.
• It is an interpreted language (means that scripts execute without
preliminary compilation).
• Everyone can use it without purchasing a license.
• It consists of lines of executable computer code.
• It is used to validate the data at the client side.
Why Scripting ?

•JavaScript was designed to add interactivity to HTML pages


•JavaScript is typically used to manipulate existing HTML
elements.
•Supports browsers like - Netscape, Internet Explorer, mozila
firefox, Opera etc.
• Programming syntax is similar with C, C++ and Java
• Supports both client and server web applications
How It Works - Steps
1. The page is loaded by the Browser
2. Browser detects JavaScript tag <script>.
3. Browser passes the script to the Interpreter.
4. Interpreter evaluates (performs) the script.
5. Browser displays page
How JavaScript Works in web?

• Web Browser executes the HTML file with embedded


JavaScript by interacting with the user
Advantages of JS
• An interpreted Language (no need of compilation).
• Simple programming statements,embedded within HTML tags.
• Minimal syntax and easy to learn.
• Easy debugging and testing.
• Platform independence and executes on client machine.
• Execution is very fast, no connection needed once loaded.
• No special tools required.
How & where to Embed JavaScript?

1. <HTML>
<HEAD>
<SCRIPT language = “JavaScript”>
// Code is Written Here
</SCRIPT>
</HEAD></HTML>
2. <HTML><HEAD></HEAD>
<BODY>
<SCRIPT language = “JavaScript”>
// Code is Written Here
</SCRIPT>
</BODY></HTML>
JavaScript Comments and variable

•Single line comments start with //.


•Multi line comments start with /* and end with */.
•Using Comments at the End of a Line.
• var x=5; // declare a variable and assign a value to it.
Variable names are case sensitive (y and Y are two different variables)
•Variable names begin with a letter, the $ character, or the underscore
character
•Syntax for variable declaration:
var x = “Hello”;
var y = 10;
Data Types

TYPE Example
String: “Hello”
Number: 4.5
Boolean: true
Null: null

A JavaScript variable can hold any data type.

Syntax for variable declaration:


var x = “Hello”;
var y = 10;
Operators

•The values to which the operator is applied called operands


•An operator is used to transfer one or more values into a single resultant values.
•The combinations of both called as expression.
Arithmetic :- +, - , /, *, %

Assignment:- +=, -=, /=, *=, %=

Relational :- >, >=, <, <=, !=

Logical :- &&, ||, !

Concat :- +
Control Structures

•If construct
if (condition)
{
statement[s] if true
}
• If . . . else construct
if (condition)
{
statement[s] if true
} else {
statement[s] if false
}
Loops

• for Loop
for ([initial expression]; [condition]; [update expression])
{ statement[s] inside loop}
• for . . . in Loop
for (foobar in object ){ statements }
• while Loop
while (condition){ statements}
• do-while Loop
do {
statements
} while (condition)
Display prime Numbers
<html>
<body>
<script language=“javascript”>
for(i=1;i<=100;i++)
{ c=0;
for(j=1;j<=i;j++)
{ if(i%j==0)
{ c=c+1; }
}
if(c==2)
{ Document.write(i+”prime”);}
}
</script>
</body>
</html>
Arrays

.
•The array is a special type of variable
Syntax :
var arrayname = new Array (size)
Example :
• To declare an array of size 5.
var foobar = new Array (5)
• To assign values to the array
foobar [0] = “Yellow”
foobar [1] = “Red”
foobar [2] = “Orange”
foobar [3] = “Green”
foobar [4] = “Black”
JavaScript Array Sorting

•JavaScript has built-in functions for arrays


<script type="text/javascript">
var myArray= new Array();
myArray[0] = "Football";
myArray[1] = "Baseball";
myArray[2] = "Cricket";
myArray.sort();
document.write(myArray[0] + myArray[1] + myArray[2]);
</script >
Arrays

• Values in an array are accessed by the array name and location.. Example: myArray[2];
<HTML><HEAD>
<SCRIPT LANGUAGE = "JavaScript">
var foobar = new Array(4)
foobar[0] = "one“;
foobar[1] = 2;
foobar[2] = 4;
foobar[3] = “4.5”;
for (var i in foobar)
{alert (i + “: ”+foobar[i]+" "+ typeOf(foobar[i]))}
</SCRIPT></HEAD></HTML>
Dense Array
• Array is initialized during declaration called dense array.

• Days=new array{‘mon’,’tue’,’wed’,’thu’,’fri’,’sat’,’sun’}.

• join(): print the array element in the single line

• reverse() :print the array elements in the reverse order.


Demo(join)
<HTML><HEAD>
<SCRIPT LANGUAGE = "JavaScript">
stud = new Array(4);
stud[0] = “Ram"
stud[1] = “Hari"
stud[2] = “Gopal“
stud[3] = “Shyam“
document.write(stud[0]+”<br>”);
document.write(stud[1]+”<br>”);
document.write(stud[2]+”<br>”);
document.write(stud[3]+”<br>”);
Join=stud.join();
document.write(Join);
rev=stud.reverse();
document.write(rev);
</SCRIPT></HEAD></HTML>
document.write() is a java script fuction used for writing out put on the screen
Functions

Syntax:
function functionName ( [parameter1]. . . [,parameterN] )
{//Satements}
Example:
<HTML><HEAD><TITLE>My First Function </TITLE><SCRIPT>
function showMsg(msg)
{ alert ("The Button Sent: " + msg) }
</SCRIPT></HEAD>
<BODY><FORM>
<INPUT TYPE="BUTTON" NAME="FOOBAR"
VALUE=" Click Me "
onClick=" showMsg('The Button Has Been Clicked')">
</FORM></BODY></HTML>
Document Object Model

window
frame sel to parent
f p

history document location toolbar, etc.

lin anchor lay for applet image ar


k er m ea

text radio button fileUpload select

textare checkb re Option


a ox set
password submit
Window Object

• Window object Access window properties.


window. propertyName or self . propertyName or propertyName
Example:
<HTML><HEAD><SCRIPT>
function showStatus(msg){
window.status = msg
return true}
</SCRIPT></HEAD><BODY>
<A HREF="hello.htm" onMouseOver = "return showStatus('This will Say
Hello')" onMouseOut= "return showStatus(' ')">
HELLO</A></BODY></HTML>
Window Object

Methods:
• alert()
• confirm()
• prompt()
• open()
• close()

Accessing window methods:


window. methodName ([parameters])
or self . methodName ([parameters])
or methodName ([parameters])
Window Object

• alert():A small pops up dialogue box and appears in front of the web page
currently in focus.
•It inform the user about the error and its problem.
Example:
<HTML>
<HEAD>
<SCRIPT>
alert ("This Is a JavaScript Alert Dialog")
</SCRIPT>
</HEAD>
</HTML>
Window Object

confirm(): It is very similar to the JavaScript alert function.


•It provides the user two choice; they can either press OK to confirm the popup's
message or they can press cancel do not agree to the popup's request
Example:
<HTML>
<HEAD>
<SCRIPT>
confirm ("This Is a JavaScript Confirm Dialog Box")
</SCRIPT>
</HEAD>
</HTML>
Window Object

• prompt():prompt is used to gather the user's information and displayed


on the screen.
Example:
<HTML><HEAD><SCRIPT>
var answer = prompt (" What Is Your Name ")
if (answer)
{
document.write ("Hello "+answer)
}
</SCRIPT>
</HEAD></HTML>
Window Object

• open() & close()


Example:
<HTML><HEAD><SCRIPT>
var newwindow
function windowopen(){
newwindow = window.open("hello1.htm","new",
"HEIGHT=200,WIDTH=300")}
function windowclose(){ newwindow.close() }
</SCRIPT></HEAD><BODY><FORM>
<INPUT TYPE="Button" onClick="windowopen()" value=" OPEN" >
<INPUT TYPE="Button" onClick="windowclose()" value="CLOSE">
</FORM></BODY></HTML>
Document Object

Methods:
• write()
Accessing document methods:
window.document. methodName ([parameters])
or document . methodName ([parameters])
Example:
<HTML>
<HEAD>
<SCRIPT LANGUAGE="JavaScript">
document.write ("<H1 align='center'>Hello World </H1>”)
</SCRIPT></HEAD></HTML>
Location Object

Properties:
• href
• pathname
Accessing location properties:
window.location. propertyName
or location.propertyName
Location Object
Example:

<html><head><title>Location Object</title></head>
<body onLoad="newwindow()">
<h1>Location Properties</h1><hr>
<script language = "javascript">
function newwindow(){
newwindow=window.open("","","HEIGHT=200, WIDTH=300")
newwindow.location.href="hello.htm"
}
document.write("<b> Location pathname = "+ location.pathname +
"</b>.")
</script></body></html>
Location Object

• Methods:
• reload()
Accessing location methods:
window.location. methodName ([parameters])
or location.methodName ([parameters])
<html><body>
<h1>This is the file for location methods !!!!!!!!</h1>
<form ><input type = "text" name = "txt" >
<input type = "button" value = "reload" width = "20" onclick = "toreload()"></form>
<script language = "javascript">
function toreload(){ location.reload(); }
</script></body></html>
History Object

• Methods
• back()
• forward()
• go(number)
Accessing document methods:
window.history. methodName ([parameters])
or history.methodName ([parameters])
Event Handlers

• onBlur:- User removes input focus from an input element.


" text
" textarea
" select
• onClick:- User clicks on an object.
" button
" link
" reset
" submit
" checkbox
" radiobutton
Event Handlers

• onChange:- User changes the value property of -


" text
" textarea
" Select

• onFocus:- User sets the focus on -


" text
" textarea
" Select

• onLoad:- User loads a document in a web browsers.


• window
Event Handlers

• onMouseOver:- User moves the mouse over -


" link
• onSelect:- User selects an item from an input field like-
" text
" textarea

• onReset:- When the reset button is clicked.
" form
• onSubmit:- When the submit button is clicked.
" form
Forms and Form Elements

Form Attributes/Properties:
name, action, method, elements[ ]
Form Elements:
• Text object
• Button object
• Checkbox object
• Select object
• Textarea
Accessing a Form:
document.forms[0] or document.formName
Accessing Form elements:
document.forms[0].elements[0] or document.forms[0].elementname or
document.forms[0].element[0] or document.formaname.elementname
Forms and Form Elements

Example:
<html><body>
<form name="frm1">
Name: <input type="text" name="myname">
<input type="button" name="sub1" value= " Show My Name " onClick="showname()">
<script language="JavaScript">

function showname(){
alert ("Your Name is " + document.frm1.myname.value)
}
</script></form>
</body>
</html>
Forms and Form Elements

Form Submission: 2 types-


• post
• get
Forms and Form Elements

Example:
<HTML><HEAD><TITLE>JavaScript</TITLE><SCRIPT LANGUAGE="JavaScript">
function checkform(form){
for (var i=0; i< form.elements.length; i++) {
if (form.elements[i].value == "") {
alert ("Fill Out All the Fields")
return false
}
return true}}
</SCRIPT></HEAD><BODY>
<FORM name="frm2" method=“post" onSubmit="return checkform(this)" action=“hello11.htm"> <pre>
<b>UserName:</b><input type="text" name="name1"><br>
<b>Password:</b><input type="password" name="passwd"><br>
<input type="submit" name="sub1" value=" Submit ">
</pre></FORM></BODY></HTML>
String Object

Declaration and Initialization


Synatx:-
var stringname = "Hello"
var stringname = new String("Hello")
Operators:- "+"
Example:-
var msg1 = "Hello"
var msg2 = "World"
var msg = msg1 + msg2
String Object

• Property:
length
Example : var len = “Hello World”.length //len=11
• Methods:-
• charAt(position):- Returns the character at that specified position.
Example:
var x = “banana”.charAt(0) //x=“b”
• indexOf(Str [, startIndex]):- Returns the index of the first
occurrence of the search string (Str).
Example: var y = “banana”.indexOf(“a”) //x=1
var y = “banana”.indexOf(“a”,2) //x=3
String Object

• Methods:-
• lastIndexOf(Str [, startIndex]):- Returns the index of the last occurrence of
the search string (Str).
Example var y = “banana”.lastindexOf(“a”) //x=5
substr(start [, len]):- Returns a substring within a string .
Example
var str1 = “Hello”.substr(0,4) //str1 = “Hell”
• toUpperCase():-
"var upstr =“hello”.toUpperCase() // upstr=“HELLO”
• toLowerCase():-
"var lowstr =“HELLO”.toLowerCase() // lowstr=“hello”
Math Object

Properties:
• isNAN(value) : Checks whether the value is a number or not
• parseInt(string) : Converts a string to an integer.
• parseFloat(string) : Converts a string to a float.
Math Object

Example:
<html><body>
<script language="javascript">
var str = "40.6"
document.write ("<br>str is <b>" + str + "</b> str is of type <b>" + typeof(str))

var num = parseInt(str)


document.write ("</b><br>num is <b>" + num + "</b> num is of type <b>" + typeof(num))

var fnum = parseFloat(str)


document.write ("</b><br>fnum is <b>" + fnum + "</b> fnum is of type <b>" + typeof(fnum))
</script>
</body></html>
Date Object

Methods:
• getDate() : Returns the day of the month. (Range is 1 to 31)
• getDay() : Returns the day of the week. (Range is 1 to 7)
• getHours() : Returns the number of elapsed hours in the day. (Range- 0 to 23)
• getMinutes() : Returns the number of elapsed minutes in an hour. (Range- 0 to
59)
• getSeconds() : Returns the number of elapsed seconds in a minute. (Range- 0 to
59)
• getMonth() : Returns the month of the year. (Range- 0 to 11)
• getYear() : Returns the calendar year. (Range- 1970 onwards)
• getTime(): Returns the number of milliseconds elapsed since January
1970.
Date Object

• setDate(date) : Sets the day of the month as the date


• setDay(day ) : Sets the day of the week as the day
• setHours(hour) : Sets the number of elapsed hours in the day as the
hour
• setMinutes(minutes) : Sets the number of elapsed minutes in an
hour as the minutes.
• setSeconds(seconds) : Sets the number of elapsed seconds in a
minute as the seconds.
• setMonth(month) : Sets the month of the year as the month.
• setYear(year) : Sets the calendar year as the year.
Date Object

Usage:
new Date (“Month, dd, yyyy, hh:mm:ss”)
new Date (“Month, dd, yyyy”)
new Date (yy,mm,dd,hh,mm,ss)
new Date (yy,mm,dd)
new Date (milliseconds)
Example:

var today = new Date();


var myBirthDay = new Date(“September 01, 1980”)
Date Object

Example:
<html><body>
<script language="javascript">
var today = new Date();
var myBirthDay = new Date(“MAY 14, 1980")
document.write ("Today is <b>" + today)
document.write ("<br></b> MyBirthDay is<b> " + myBirthDay + "</b>")
document.write ("<br>My Date of Birth is<b> " + myBirthDay.getDay() + "</b>");
document.write ("<br>My Year of Birth is<b> " + myBirthDay.getYear() + "</b>");
myBirthDay.setYear(80)
document.write ("<br>My New Year of Birth is<b> " + myBirthDay.getYear() +
"</b>");
</script></body></html>
LOCAL STORAGE &SESSION
STORAGE
Local storage is a feature in web browsers that allows
developers to save data in the user’s browser. It’s part
of the web storage API, together with session storage.
• Local storage works by accepting data in key-value
pairs. It retains the data even when the user refreshes
the page or closes the tab or browser.
DIFFERENCE
The key differences between the two are the lifespan of
the stored data and their scope.
Data in local storage remains available even when the
tab/browser is closed. But closing the tab/browser clears
any data stored in session storage.
• Also, data in local storage is accessible across multiple
browser tabs and windows. On the other hand, data in
session storage is only accessible within specific
browser tabs and is not shared.
How to Store Data in Local
Storage
• To store data in local storage, you use the setItem()
method. This method takes in two arguments, a key and
a value.
• localStorage.setItem(key,value);
How to Read Data From Local
Storage
• To retrieve and use data from local storage, you use the
getItem() method. This method takes in a key as an
argument.
• localStorage.getItem(value);
How to Store and Read Complex Data Values in Local
Storage

• Local storage can only store strings. This means if you


need to store values like objects or arrays, you first
need to get a string representation of the value. You do
this using the JSON.stringify() method.
• Eg:
• const userObj = { username = “abz", email:
[email protected]"}localStorage.setItem('user',
JSON.stringify(userObj))
How to Delete Data from Local
Storage
• There are two methods available for deleting data from
local storage. One is the removeItem() method and the
other is the clear() method.
• removeItem() method when you want to delete a single
item from local storage or else clear() is been used.
• localStorage.removeItem(key)
• localStorage.clear()
How to Get the Name of a Key in Local Storage

• key() method to get the name of a key at a particular


index in local storage
• Eg:localStorage.key(0)
• It will return the name of the key at index 0. If there is
no key at the specified index, the method will return
null.
Benefits

1.Persistent data: When you use local storage, the stored data
remains even when the user closes the tab or the browser. This
is useful for saving user preferences, settings, and other
relevant data. It can help create a seamless user experience.
2.Offline access: You can use local storage as a means to cache
data which can be accessed even with limited or no internet.
This makes it a useful feature for apps that rely on caching data
for offline use like news readers, productivity apps, and so on.
3.More storage capacity: Compared to other storage means,
local storage has a relatively high capacity. For example,
cookies are limited to 4 kilobytes per domain. But local storage
can store up to 5 megabytes of data per domain.
Limitations

1.Stores only strings: As you learned earlier, local storage can only store string
values. You can use the JSON stringify and parse methods to work around it.
But some web developers may not prefer it as it can lead to writing complex code
that’s difficult to debug.
2.Security concerns: Data in the local storage can be prone to attacks like
cross-site scripting (XSS). As such, you should be cautious when working with
sensitive information. It’s advisable to assess security implications and consider
other alternatives where necessary.
3.Not accessible to web workers: Local storage is part of the Window object.
As such, it’s tied to the main execution thread of the web page. This means it's
not accessible to web workers. So if you run any background processes, you
cannot use local storage within the web worker scripts.

You might also like