Sei sulla pagina 1di 49

Introduction

• JavaScript is the scripting language of the Web!


• JavaScript is used in millions of Web pages to
improve the design, validate forms, detect browsers,
create cookies, and much more.
• The HTML <script> tag is used to insert a JavaScript
into an HTML page.
• JavaScript is the most popular scripting language on
the internet, and works in all major browsers, such as
Internet Explorer, Mozilla, Firefox, Netscape, and
Opera.
• JavaScript was designed to add interactivity to
HTML pages
• JavaScript is a scripting language (a scripting
language is a lightweight programming
language)
• A JavaScript consists of lines of executable
computer code
• A JavaScript is usually embedded directly into
HTML pages
• JavaScript is an interpreted language (means
that scripts execute without preliminary
compilation)
• Everyone can use JavaScript without purchasing
a license
• JavaScript = ECMAScript
• •JavaScript is an implementation of the ECMAScript
language standard.
• ECMA-262 is the official JavaScript standard.
• JavaScript was invented by Brendan Eich at Netscape
(with Navigator 2.0), and has appeared in all browsers
since 1996.
• The official standardization was adopted by the ECMA
organization (an industry standardization association) in
1997.
• The ECMA standard (called ECMAScript-262) was
approved as an international ISO (ISO/IEC 16262)
standard in 1998.
What can a JavaScript Do?
• JavaScript gives HTML designers a
programming tool - HTML authors are
normally not programmers, but JavaScript is a
scripting language with a very simple syntax!
Almost anyone can put small "snippets" of code
into their HTML pages
• JavaScript can put dynamic text into an
HTML page - A JavaScript statement like this:
document.write("<h1>" + name + "</h1>") can
write a variable text into an HTML page
• JavaScript can react to events - A JavaScript
can be set to execute when something
happens, like when a page has finished loading
or when a user clicks on an HTML element
• JavaScript can read and write HTML elements - A
JavaScript can read and change the content of an HTML element
• JavaScript can be used to validate data - A JavaScript can be
used to validate form data before it is submitted to a server. This
saves the server from extra processing
• JavaScript can be used to detect the visitor's browser - A
JavaScript can be used to detect the visitor's browser, and -
depending on the browser - load another page specifically
designed for that browser
• JavaScript can be used to create cookies - A JavaScript can be
used to store and retrieve information on the visitor's computer
• It can be used in windows to automate computer –
administration tasks and inside Acrobat also.
Tools Needed
• Simple Text editor – Such as notepad
• Any HTML Editor
• Microsoft’s Visual Web developer Express Edition
• Adobe Dreamweaver
• Microsoft Visual studio
• Web browser
Where to put
• JavaScripts in the body section will be executed WHILE the page
loads.
• JavaScripts in the head section will be executed when CALLED.
• Browsers such as IE and Firefox use javascript as their default
script language.
• Scripts in the head section: Scripts to be executed when they
are called, or when an event is triggered, go in the head section.
When you place a script in the head section, you will ensure that
the script is loaded before anyone uses it.
• Scripts in the body section: Scripts to be executed when the
page loads go in the body section. When you place a script in the
body section it generates the content of the page.
• Scripts in both the body and the head section: You can place
an unlimited number of scripts in your document, so you can
have scripts in both the body and the head section.
• Using an External JavaScript
• same JavaScript on several pages, without having to write the
same script on every page.
• To simplify this, you can write a JavaScript in an external file.
Save the external JavaScript file with a .js file extension.
Note: The external script cannot contain the <script> tag!
• To use the external script, point to the .js file in the "src"
attribute of the <script> tag.
<script type=“text/javascript” src= “a.js”></script>
we should not put any code within the script tag.
Advantages of External File:
1) Reusability
2) Browser will catche them. This could save download time and
reduce bandwidth usage.
First program :
<html>
<body bgColor=“blue”>
<script type="text/javascript">
document.write("Hello World!")\
document.bgColor=“Red”;
</script>
</body>
</html>
• Second Program :
<html>
<body>
<p id=“my1”> </p>
<script type=“text/javascript”>
document.getElementById(‘my’).innerHTML= “ Hi
Welcome to Javascript world”;
</script>
</body>
</html>
Introduction
• JavaScript is a sequence of statements to be executed by the browser.
• Semicolon separates JavaScript statements.
• We add a semicolon at the end of each executable statement.
• JavaScript code (or just JavaScript) is a sequence of JavaScript
statements.
• Each statement is executed by the browser in the sequence they are
written.JavaScript statements can be grouped together in blocks.
• Blocks start with a left curly bracket, and end with a right curly
bracket.The purpose of a block is to make the sequence of statements
execute together.
• The statements grouped together in blocks, are JavaScript functions.
• JavaScript is case sensitive.
• Single line comments start with //.
• Multi line comments start with /* and end with */.
Variables
Programming
• A variable is a "container" for information you want to store. A variable's
value can change during the script. You can refer to a variable by name to see
its value or to change its value.

Rules for variable names:


• JavaScript variables can be used to hold values or expressions.
• Variable can have short names or more descriptive names.
• Variable names must begin with a letter .
• Variable names can also begin with $ and _ .
• Variable names are case sensitive.
• JavaScript variables can also hold other types of data, like text values.
• JavaScript variables are declared with the var keyword
The datatypes supported are String, Number, Boolean, Array, Object, Null,
Undefined.
• A string is a variable which stores a series of characters
• JavaScript has only one type of numbers. Numbers can be written with, or
without decimals.
• Booleans can only have two values: true or false.
• Undefined is the value of a variable with no value.
• Variables can be emptied by setting the value to null;
• An object is delimited by curly braces. Inside the braces the object's
properties are defined as name and value pairs (name : value). The
properties are separated by commas:
var person={fname:”komal", lname:”valli", id:1234}; It can be
accessed by two ways :
document.write(person.fname) or d.w(person[“fname”])
• JavaScript variables are all objects. When you declare a variable you
create a new object.
• When we declare a new variable, we have to declare its type using
the "new" keyword
var a= new String;
• For conversion,parseInt, parseFloat functions are available.
Lifetime of Variables
• When you declare a variable within a function, the variable
can only be accessed within that function.

• When you exit the function, the variable is destroyed.


These variables are called local variables.
• You can have local variables with the same name in
different functions, because each is recognized only by the
function in which it is declared.
• If you declare a variable outside a function, all the
functions on your page can access it. (after the script tag)
• The lifetime of these variables starts when they are
declared, and ends when the page is closed.
Array

• The Array object is used to store multiple values in a single


variable.
• An array can be defined in three ways.
• var myColors=new Array();
• var myColors=new Array(“red",”blue",”green”);
• var myColors=[“red",”blue",”green"]
• You can refer to a particular element in an array by referring to
the name of the array and the index number. The index number
starts at 0.
• Dummy= new Array(“a1”,”a2”,100, true,3.14,new Array(2,2))
Functions
• A function is a block of code that will be executed when we call that.
• A function is written as a code block (inside curly { } braces), preceded by the
function keyword:
Ex : function funcname()
{}
• The function can be called directly when an event occurs (like when a user
clicks a button), and it can be called from "anywhere" by JavaScript code.
• Arguments can be passed to the function .
function funcname(arg1,arg2,….) { }
• We can return the value from the function. Just we have to mention the return
line in the function block.
Operators
• Operators are used to handle variables.
• Types of operators
– Arithmetic operators
– Comparisons operators
– Logical operators
– Assignment and String operators.
– Conditional operator
– The + operator can also be used to add string variables or
text values together.
Control flow and loops
• if statement - use this statement to execute some code only if a
specified condition is true
• if...else statement - use this statement to execute some code if the
condition is true and another code if the condition is false
• if...else if....else statement - use this statement to select one of many
blocks of code to be executed
• switch statement - use this statement to select one of many blocks of
code to be executed
• for - loops through a block of code a specified number of times
• while - loops through a block of code while a specified condition is true
• The for...in statement loops through the properties of an object.
for (variable in object)
{
code to be executed
}
Objects
• Objects refers to windows, documents, images, tables, forms,
buttons or links, etc.
• Objects should be named.
• Objects have properties that act as modifiers.
• In JavaScript, objects are data (variables), with properties and
methods.
Creating Objects
var student = new Object();
student.fname=“jkl”;
student.rollno=100;
• For Accesssing object,
• objectName.propertyName
• objectname.methodname()
<html>
<body>
<script>
function person(firstname,lastname,age)
{
this.firstname=firstname;
this.lastname=lastname;
this.age=age;
}
myFather=new person(“komal”,”valli“,40);
document.write(myFather.firstname + " is " + myFather.age + " years old.");
</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.
Properties
Properties are the values associated with an object
<script type="text/javascript">
var txt="Hello World!";
document.write(txt.length);
</script>

Methods
Methods are the actions that can be performed on objects.
<script type="text/javascript">
var str="Hello world!";
document.write(str.toUpperCase());
</script>
Methods
• Methods are actions applied to particular objects. Methods are
what objects can do.
– e.g., document.write(”Hello World")
– document is the object. write is the method.
• function person(firstname,lastname,age)
{ this.firstname=firstname;
this.lastname=lastname;
this.age=age;
this.changeName = function (name)
{
• this.lastname = name;}}
Ex: var obj1 =new person(“komal”,”valli”,40);
obj1.changeName(“chakra”);
JavaScript is prototype based, not class based.
Events
• Events associate an object with an action.
– e.g., the OnMouseover event handler action can
change an image.
– e.g., the onSubmit event handler sends a form.
• User actions trigger events.
Popup Boxes
• JavaScript has three kind of popup boxes: Alert box,
Confirm box, and Prompt box.
• Alert Box
• An alert box is often used if you want to make sure information comes
through to the user.
• When an alert box pops up, the user will have to click "OK" to proceed.
Ex: alert(text)
• Confirm Box
• A confirm box is often used if you want the user to verify or accept
something.
• When a confirm box pops up, the user will have to click either "OK" or
"Cancel" to proceed.
• If the user clicks "OK", the box returns true. If the user clicks "Cancel", the
box returns false.
Ex: confirm("sometext");
• Prompt Box
• A prompt box is often used if you want the user to input a value before
entering a page.
• When a prompt box pops up, the user will have to click either "OK" or
"Cancel" to proceed after entering an input value.
• If the user clicks "OK" the box returns the input value. If the user clicks
"Cancel" the box returns null.
Ex: prompt("sometext","defaultvalue");
Exception
• The try...catch statement allows you to test a block of code for
errors.
• Syntax :
try
{
//Run some code here
}
catch(err)
{
//Handle errors here
}
• The throw statement can be used together with the try...catch
statement, to create an exception for the error.
HTML DOM
• With the HTML DOM, JavaScript can access all the elements of an HTML
document.
• 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:
• 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 react to all the events in the page.
• If we want to manipulate HTML elements, first we have to access the
elements :
 Finding HTML elements by id - getElementById(“t1");
 Finding HTML elements by tag name –getElementsByTagName(“p”)
 Finding HTML elements by class name(CSS)
• The HTML DOM allows JavaScript to change the content of HTML
elements.
• The easiest way to modify the content of an HTML element is by using the
innerHTML property.
Ex: document.getElementById(id).innerHTML=new HTML
• HTML attribute also can be changed.
Ex : document.getElementById(id).attribute=new value
• The HTML DOM allows JavaScript to change the style of HTML elements.
Ex: document.getElementById(id).style.property=new style
• HTML DOM allows JavaScript to react to HTML events.
• HTML DOM allows to create the elements also.
document
• Manipulate document that is currently visible in the
browser window
• - Every Document object has:
• - forms - an array of references to the forms of the
document
• Each Form object has an elements array, which has
references to the form’s elements
• Document also has anchors, links, & images
• Properties:
• cookie - Used to identify the value of a cookie.
• defaultCharset
• domain - The domain name of the document server.
• embeds - An array containing all the plugins in a
document.
• fgColor - The text color attribute set in the <body> tag.
• File
• CreatedDate - Use this value to show when the loaded
HTML file was created
• fileModifiedDate - Use this value to show the last change
date of the loaded HTML file
• fileSize
• fileUpdatedDate
• lastModified - The date the file was modified last.
• layers - An array containing all the layers in a document.
• linkColor - The color of HTML links in the document. It is
specified in the <body> tag.
• location
• mimeType
• nameProp
• protocol
• referrer - The Universal Resource Locator (URL) of the
document that we got the link to the present document
from.
• title - The name of the current document as described
between the header TITLE tags.
• URL - The location of the current document.
• vlinkColor - The color of visited links as specified in the
<body> tag
• close() - Closes an output stream that was
used to create a document object
• Write(String)
• Writeln(string)
• open([mimeType]) - Opens a new
document object with the optional MIME
type
Window
• Properties:
• clientInformation
• closed - A boolean value that indicates whether the
window is closed.
• defaultStatus - This is the default message that is loaded
into the status bar when the window loads.
window.defaultStatus = "Click on a link on the left to
navigate this website."
• event
• external
• lastModified
• length - The number of frames that the window contains
• Methods :
alert(string)
blur()
clearInterval(interval)
clearTimeout(timeID)
close()
confirm("message")
focus()
open("URLname","Windowname",["options"])
• moveBy(x,y) - The window is moved the specified number
of pixels in the X and Y direction.
• moveTo(x,y) - The window is moved to the specified X and
Y pixel location in the browser
• prompt("message","defaultmessage") - A prompt dialog box is
displayed with the message passed as the prompt question or phrase.
The defaultmessage appears in the box, to be replaced by user
entered text. If no default message string is present, no default string
is displayed.
• resizeBy(X,Y) - Adjusts the window size relative to the current value.
• resizeTo(X,Y) - Adjusts the window size to set X and Y width and
height values.
• scroll(X,Y) - The window is scrolled to the location specified by the X
and Y values in pixels.
• scrollBy(X, Y)
• scrollTo(X,Y)
• setInterval(function(),milliseconds,[functargs]) - Cause a function to be
called periodically based on the time value specified. The functargs
are arguments passed to the function.
• setTimeout(function(),milliseconds,[functargs]) - Used to call a function
after the specified time in
Screen

• The window.screen object contains information about the user's


screen.
• The window.screen object can be written without the window
prefix.
Properties :
• screen.availWidth - available screen width
• screen.availHeight - available screen height
Number
• JavaScript numbers can be written with, or without decimals:
• JavaScript is not a typed language. Unlike many other programming
languages, it does not define different types of numbers, like integers, short,
long, floating-point etc.
• All numbers in JavaScript are stored as 64-bit (8-bytes) base 10, floating
point numbers.
• JavaScript interprets numeric constants as octal if they are preceded by a
zero, and as hexadecimal if they are preceded by a zero and x.
• Properties :
MAX_VALUE, MIN_VALUE ,NAN
• Methods
toString(), valueOf()
String Object
• The String object is used to manipulate a stored piece of
text.
• String objects are created with new String().
• Property:
length
• Methods:
i) charAt(index)
ii) indexOf (searchstring, start)
iii) split(separator, limit)
iv) substr (start,length)
v) toLowerCase()
vi) toUpperCase()
Date Object
• The Date object is used to work with dates and times.
• Date objects are created with the Date() constructor.
• getDate()
• getDay()
• getTime()
• getMonth()
• getYear()
• getMinutes()
• Navigator Object
• The navigator object contains information about the browser
• History Object
• The history object contains the URLs visited by the user (within
a browser window).
• The history object is part of the window object and is accessed
through the window.history property.
• Location Object
• The location object contains information about the current URL.
• The location object is part of the window object and is accessed
through the window.location property.
Navigator Object Properties
Property Description
appCodeNameReturns the code name of the browser
appName Returns the name of the browser
appVersion Returns the version information of the
browser
cookieEnabledDetermines whether cookies are enabled in
the browser
platform Returns for which platform the browser is
compiled
useAgent Returns the user-agent header sent by the
browser to the server
• History Object Properties
• Property Description
• length Returns the number of URLs in the history list
• History Object Methods
• Method Description
• back() Loads the previous URL in the history list
• forward() Loads the next URL in the history list
• go() Loads a specific URL from the history list
• Location Object Properties
• Property Description
• hash Returns the anchor portion of a URL
• host Returns the hostname and port of a URL
• Hostname Returns the hostname of a URL
• Href Returns the entire URL
• pathname Returns the path name of a URL
• port Returns the port number the server uses for a URL
• protocol Returns the protocol of a URL
• assign() Loads a new document
• reload() Reloads the current document
• replace() Replaces the current document with a new one
Image object
• The Image object represents an embedded image.
• For each <img> tag in an HTML document, an Image object is
created. The <img> tag creates a holding space for the referenced
image.
• Properties:
Align, alt,src,border,height,width,name,vspace,hspace
• Events:
• onLoad, onabort,onError
• Style object
• The Style object represents an individual style statement.
• The Style object can be accessed from the document or from the
elements to which that style is applied.
• Syntax for using the Style object properties:
• document.getElementById("id").style.property="value"
Anchor Object
• The Anchor object represents an HTML hyperlink.For each <a> tag
in an HTML document, an Anchor object is created.
• An anchor allows you to create a link to another document (with the
href attribute), or to a different point in the same document (with the
name attribute).
• You can access an anchor by using getElementById(), or by
searching through the anchors[] array of the Document object.
• Properties: href,name,target
FORM
• The Form object represents an HTML form.
• For each <form> tag in an HTML document, a Form object is
created.
• Forms are used to collect user input, and contain input elements
like text fields, checkboxes, radio-buttons, submit buttons and
more.
• A form can also contain select menus, textarea, fieldset, legend,
and label elements.
• Forms are used to pass data to a server.
• Properties: name,method,action,length
• Methods : submit(),reset()
• Events : onsubmit, onreset
Cookies
• It is a plain text that is stored in the user’s hard drive.
• Using document object, we can create ,read and delete the
cookies.
• The following fields are important
• Expires : The date the cookie will expire. If this is blank, the
cookie will expire when the visitor quits the browser.
• Domain : The domain name of your site.
• Path : The path to the directory or web page that set the cookie.
This may be blank if you want to retrieve the cookie from any
directory or page.
• Secure : If this field contains the word "secure" then the cookie
may only be retrieved with a secure server. If this field is blank,
no such restriction exists.
• Name=Value : Cookies are set and retrieved in the form of key
and value pairs.

Potrebbero piacerti anche