- Developed by Netscape Corporation known as “Live Script”
- It was later renamed to its present name by Netscape, which had a joint venture with Sun Microsystems
- JavaScript supports server-side scripting also, separately known as Livewire
- First supported in Netscape Navigator 2.0.
- Now - Internet Explorer from Microsoft, Personal Web Client 3.0 from Lotus and Mosaic 2.0 and so on.
- JavaScript was also referred to as ECMA Script. ECMA is the short form for European Computer Manufacturer’s Association.
JavaScript Vs Java
- JavaScript has nothing to do with Java language
- Java is purely an object-oriented language, JavaScript is just a scripting tool
- JavaScript is not compiled and executed; the client directly interprets it
- JavaScript is a freely typed language whereas Java is a strongly typed one
- Object references must exist at compile-time in Java (static binding) whereas they are checked only at runtime in JavaScript (dynamic binding)
JavaScript Characteristics
- JavaScript adopts an object-based technology
- It is not purely object-oriented
- Using JavaScript, we can create objects of our own
- JavaScript is platform independent. We will be coding our scripts inside a HTML page, and they are not dependent on any specific platform. They rely on user agents. In most of the cases, browsers play a role as user-agents.
- It is based on an event-driven model
JavaScript Advantages
- control the frame navigation
- include a plug-in or a Java applet inside a page
- Form Validation in the client’s place itself, thereby reducing the burden on the server
images can swap when the user moves a mouse over them, - calculations can be made without having to resort to a CGI script
- JavaScript timer on the client to check how much time he/she takes to fill a form.
- Apart from all these advantages, JavaScript is very easy to learn.
JavaScript Versions
- JavaScript 1.0
Mathematical calculations, provide programming structures like statements and functions and do things to HTML elements
Can read out or write into form elements, load new pages into another frame or window, on the page and do calculations with date and time - JavaScript 1.1
Support for changing images, the mouse over script, and the support of window focus. Graphical effects were also possible. - JavaScript 1.2
Support of DHTML - JavaScript 1.3,
Level 1 DOM has been implemented in all browsers
JavaScript Compatibility
- 1995-1996
JavaScript 1.0
Netscape Navigator 2.0, Microsoft Internet Explorer 3.0, - 1996
JavaScript 1.1
Netscape Navigator 3.0, Hot java 3, Opera 3 - 1997
JavaScript 1.2
Netscape Navigator 4.0, Microsoft Internet Explorer 4.0, Netscape 4, Explorer 4, Opera 4, Omni web, Opera 5 - 1998-1999
JavaScript 1.3
Netscape Navigator 4.5+, Microsoft Internet Explorer 5+
User Interactivity through JavaScript
Functions used to interact with the client
alert()
prompt()
The alert method displays a dialog box in the browser with the text string passed as an argument
The prompt method is used get some information from the user
It displays a prompt dialog box and captures the value entered by the user.
We can store the value entered by the user in a variable
Programming JavaScript
Data Types
Number
4.5, 8.2, 7
Any number either it’s a positive, negative or zero or decimal
Boolean
true, false
A logical true or false
String
“Center”, “Ship!”
Any string inside the quotation marks. Special characters are also allowed.
Object
Car, book
Any “thing” that has got methods and properties
Function
alert(), confirm()
Definition of a function
Variables
Variables can be created using var keyword
var temp
var onemoretemp, strtemp
Assigning values to variables
temp = 45
onemoretemp = temp
strtemp= ”temp value”
Operators
Addition (+)
Subtraction (-)
Multiplication (*)
Division (/)
Modulus (%)
String concatenation operator is “+”
Pre-increment operator and post-increment operators (++)
Pre-decrement and post-decrement operators (--)
NOT ( ! )
Bit wise XOR ( ^ )
AND ( && )
Shift Left ( << ) OR ( ) Shift Right Zero fill ( >>> )
Bit wise AND ( & )
Shift Right with Sign ( >> )
Bit wise OR ( )
Identity ( === )
Bit wise NOT ( ~ )
Non identity (!= )
Arrays
Used to store multiple data, based on an index, in one storage structure
The index starts from zero
var k=new Array();
var t=new Array(“rama”, “rahim”, “Robert”,5,8);
document.write(t[0]);
JavaScript supports multi-dimensional arrays also.
Data Type Conversions
JavaScript is a dynamically typed language
var answer = 42
answer = "Thanks for all the fish..."
We can convert a number in to string and vice versa
parseInt method - used to convert a string value, which is holding a number data type
temp = parseInt(“42”)
anoth = parseInt(“54.34”)
Str=””+2500;
Str=””+temp;
Simply adding an empty quote to a number value will convert a number into string data type.
Decision Constructs
If…else
If (condition)
{
statements, if it is true
}
else
{
statements if it is false
}
For Multiple Conditions
if(condition){
Statements
}
else if (condition) {
statements
}
Sample Program
var type;
type=prompt("enter the user type","");
if(type=="admin")
document.write("Welcome Administrator");
else if(type=="user")
document.write("Welcome user");
else
document.write("Sorry…");
Switch…case
Used for multiple conditions
Sample Program
var type;
type=prompt("Enter the user type","");
switch(type)
{
case "admin": document.write("Welcome Administrator"); break;
case "user": document.write("Welcome user"); break;
default: document.write("Sorry…");
}
Loops
The while and for statements are used to execute a block of code for as long as a certain condition is valid
while(expression)
{
Statements
}
for(initialization; condition; increment/decrement)
{
one or more statements
}
The break statement is used to exit a loop such as from for or while blocks
Sample Program
var i;
document.write("
| ",i," | ",i*i," |
Functions or Methods
Group of code that handles actions invoked by event handlers (more on this, later) or by simple statements
reduces the writing of the code again and we can reuse the same
Two types:-
built-in functions and user-defined functions
Built-in functions - functions which are already existing in the language itself
E.g., parseInt, alert, prompt etc.,
User-defined functions - written by the user to make our scripts scalable
Syntax for a function is as follows.
function functionname(arg1,arg2….)
{
Body
}
Sample Program
function givehalfvalue(k)
{
return k/2;
}
function displayargs()
{
document.write("
","Arguments passed to this function are:-
");
for(i=0;i
}
var i;
i=prompt("Enter either 1 or 2","");
if (i==1)
{
alert("You have chosen givehalfvalue function");
i=givehalfvalue(i);
document.write(i);
}
else if (i==2)
{
alert("You have chosen display args function");
tot=prompt("How many arguments are you going to enter","Enter a number please");
var args=new Array();
for(i=0;i
Similar to the alert method
Displays a dialog box and asks the user to proceed further or not
Returns either TRUE or FALSE based on the selection during the method call
Method brings up a dialog box that prompts the user to select either 'o.k.' or 'cancel', the first returning TRUE and the latter, FALSE
Sample Program
var opt;
opt=confirm("Do you want to delete all the records?");
if(opt)
alert("Your Records will be deleted !!!");
else
alert("No deletion of the records !!!");
Events & Event Handlers
JavaScript is based on event-driven model
Predetermined events and event handlers that deal with those events
Event handlers fire those events whenever that event happens.
Events
Blur : Occurs when the focus is removed
Focus : Occurs when the user gives input or focus to an element in the form
Change : ccurs when the user changes some value of a field
Click : Arises when the user clicks on a link or an element in the form
Double Click : Occurs when the user double clicks
Key Down : Occurs when the key makes its first contact
Key Up : When the contact with the key is released
Load : Occurs when the page is loaded
UnLoad : Occurs when the current window is cleared from view
Error : Occurs when there is a transfer error
Mouse Down : Occurs when the user presses any of the buttons of a mouse
Mouse Up : Occurs when the user releases the button.
Mouse Over : Occurs whenever the cursor rolls into the rectangular space of the object in the screen
Mouse Out : Occurs when the cursor is moved outside the rectangle space
Submit : When the user submits a form of a page
Reset : Whenever the form is reset
Select : Occurs when the option is selected
Resize : If the user resizes the window
Events & Objects
Each and every element of the form will have some restricted events associated with it
Blur - Button, Checkbox, File Upload, Frame, Layer, Password, Radio, Reset, Select, Submit, Text, Text area, Window
Focus - Button, Checkbox, File Upload, Frame, Layer, Password, Radio, Reset, Select, Submit, Text, Text area, Window
Change - FileUpload, Select, Text, Text area
Click - Button, Checkbox, Document, Links, Radio, Reset, Submit
Double Click - Area, Document, Links
Key Down - Document, Image, Links, Text area
Key Up - Document, Image, Links, Text area
Load - Document, Image, Layer, Window
UnLoad - Document, Window
Error - Window, Image
Mouse Down - Button, Document, Link
Mouse Up - Button, Document, Link
Mouse Over - Area, Layer, Link
Mouse Out - Area, Layer, Link
Submit, Reset - This is for a page
Select - Text, Text Area
Resize - Frame, Window
JavaScript Object Model
Models HTML documents in a very consistent and intuitive way
Provides an interface to access, navigate, and manipulate web page
DOM allows you to access and update the content, structure, and style of a document
To provide more interactive content on the Web
DOM allows HTML to be manipulated dynamically
Each HTML tag can be accessed and manipulated via its ID and NAME attributes
Each object has its own properties, methods, and events
The Object Model allows you to navigate along the document tree, up and down, and to the sides
You can use the child, parent, and sibling relationships to go from a particular point to any other point on your page tree
Model is divided into three sub-groups
Language objects
Form-field objects
Browser objects
Browser Objects
navigator
window
document
location
history
anchor
link
frame
image
Form-Field Objects
Button
Checkbox
Radio
Text
Reset
Text Area
Password
Select
Submit
Hidden
Language Objects
Date
Array
Math
String
JavaScript Object Model

Language Objects
The Date Object
All information related to date and time can be accessed
Built-in methods of JavaScript allow us to access the date and time values that are stored in a date object
getDate() Gets the number of the day (between 1 and 31)
getDay() Gets the day of the week (0 through 6, 0 is for Sunday)
getMonth() Gets the number of the month (0 through 11, 0 is for January)
getYear() Returns the year part of the date object.
getSeconds() Returns the seconds portion of the date object
getminutes() Gets the number of minutes ( 0 through 59)
getHours() Returns the hour part of the Date object
goGMTString( ) Returns the string in representing the universal date time of date object.
goLocalString() Returns the date in the local system’s format
setDate(), setMonth(), setYear(), setHours(), setMinutes(), setSeconds() and setTime() methods to assign values to the Date object
Sample Program:
date = new Date();
document.write(date.getMonth());
The Math Object
Commonly used methods of the Math object
abs(number) -- Returns the absolute value
ceil(numb) -- Returns the smallest integer greater than or equal to the number
floor(number) -- Returns a largest number less than or equal to the number
sin(numb) -- Returns the sine of the number
cos(numb) -- Returns the cosine of the number
tan(number) -- Returns the tangent of the number
acos(number) -- Returns arccosine of the number
asin(number) -- Returns arcsine of the number
atan(number) -- Returns arctangent of the number
sqrt(number) -- Returns the square root of the number
round() -- Returns a number to its nearest integer
max(num1,num2) -- Returns the largest of two arguments
min(num1,num2) -- Returns the smallest of two arguments
log(num) -- Returns the natural logarithm(base E) of the number
exp(num) -- Returns exponential value of the number
random() -- Returns a random number between 0 and 1
pow(x,y) -- Returns the x to the power of y value
The String Object
Although JavaScript is not a “strongly typed” language, we still need to be aware of their impact on the way we work in the Forms
Length is the main property of the String object
It gives us the total number of characters in the string.
Commonly used methods of the String object
charAt(index) -- Returns one-character from the string based on the specified index
lastIndexOf(searchstring) -- Returns the index value of the last character within the string where the searchstring begins
indexOf(searchstring) -- Returns the index value of the first occurrence of the searchstring
concat(string) -- Returns the combined string
replace(expression, replacestr) -- Replaces all that matched expressions with the replacestr and returns the replaced string
search(expression) -- Returns the offset integer of the matching expression
slice(startindex) -- To extract a portion of one string and to create a new string as a result (without modifying the original string)
split(delimeter) -- Splits the string based on the delimiter specified and return an array of delimited items.
substring(i1,i2) -- To extract a copy of a substring starting from index i1 till i2 from the original string.
toLowerCase(),toUpperCase() -- Converts the string to lowercase and uppercase characters.
Methods used to format the strings in JavaScript
String.bold() -- Makes the string in to bold face
String.fontcolor(color) -- Converts the string to the color specified
String.italics() -- Makes the string italicized
String.big(),String.small() -- Increases or decreases the weight of the font
String.fontsize(number) -- Converts the string with the font number specified
String.link(URL) -- Links the string to the specified URL
Browser Objects
Window Object
Creating a Window
Its not possible to create the main window of the browser
Once the main window is open, we can generate as many sub-windows as possible through JavaScript.
window.open() is the method used to create the new window
Paremeters required
URL of the document to load
the name of the document
the physical properties of the window
Third parameter - the physical properties of the window is used to position the new window in the screen.
left - Specifies the left x coordinate on the screen, to open the window.
top - Specifies the top y coordinate on the screen, to open the window.
scrollbars - Creates scroll bars when the page grows beyond the current screen.
location - Creates location field.
toolbar - Displays the standard toolbar.
menubar - Creates menu at the top of the window.
resizable - Enables/disables resizing of the window by the user.
width, height - Specifies the width and height of the window in pixels.
statusbar - Displays the status bar of the window.
Closing a Window
windowname.close() is used to close a particular window
Sample Program :
1) var nwindow = window.open("clock.htm","first","height=300,width=200");
2) var nwindow = window.open("clock.htm","first","height=300,width=200, scrollbar=no, location=no, resizable=no,menubar=no");
3) document.write("Close");
Location Object
Represents the URL loaded into the window
Used to navigate to a page in our own site or any other page in the Internet
location.href = “http://www.shyamsrinivas.info/”
newwin.location.href = “./bankbalance.asp”
Sample Program :
var nwindow = window.open("clock.htm","first","height=300,width=200");
location.href = "http://www.shyamsrinivas.info/";
nwindow.location.href = http://www.shyamsrinivas.info/;
History Object
Every time we visit a page, it will get stored in the history list
Whenever we press the forward or back buttons in our browser we are accessing the history.back() and history.forward() methods of the history object
forward()
Sends the user to the next page, according to the history list
back()
Sends the user to the previous page, according to the history list
Document Object
The document object we can access each and every element inside the HTML page
Sample Program :
document.write("Foreground Color = ",document.fgColor)
document.write("
")
document.write("Background Color = ",document.bgColor)
document.write("
")
document.write("Active Links Color = ",document.alinkColor)
document.write("
")
document.write("Visted Links Color = ",document.vlinkColor)
document.write("
")
document.write("Link Color = ",document.linkColor)
document.write("
")
document.write("File Creation Date = ",document.fileCreatedDate)
document.write("
")
document.write("File Modified Date = ",document.fileModifiedDate)
document.write("
")
document.write("Total File Size =",document.fileSize)
document.write("
")
document.write("Last Modified Date = ",document.lastModified)
document.write("
")
document.write("Total Anchors = ",document.anchors.length)
document.write("
")
document.write("Total Form Elements = ",document.forms.length)
Methods of the document Object
write() Writes the text of content to the document
clear() Clears the document window
Image Object
We can manipulate the properties of the images using this object
All the images inside a particular document are stored in the images array
document.images[0].src=”first.jpg”
Form Object
Provides us an opportunity to access the forms inside a document
All the forms are contained in an array, which starts from 0
We can give the form name itself as a parameter to access a particular form
document.forms(“myform”) or document.forms(0)
Form-Field Objects
Accessing Form Fields
To access a form object, we can refer it either by its name or by its index number in the form elements array
document.forms[0].elements[0].value or
document.myform.userid.value
The form array will hold all the elements in the form including submit and reset button, if available
1 comment:
Very well done
Post a Comment