Javascript
Javascript
Lecture-13
Java Script
JavaScript is the premier client-side interpreted scripting language. It‟s widely used in tasks
ranging from the validation of form data to the creation of complex user interfaces. Dynamic
HTML is a combination of the content formatted using HTML, CSS, Scripting language and
DOM. By combining all of these technologies, we can create interesting and interactive websites.
History of JavaScript:
Netscape initially introduced the language under the name LiveScript in an early beta release of
Navigator 2.0 in 1995, and the focus was on form validation. After that, the language was
renamed JavaScript. After Netscape introduced JavaScript in version 2.0 of their browser,
Microsoft introduced a clone of JavaScript called JScript in Internet Explorer 3.0.
What a JavaScript can do?
JavaScript gives web developers a programming language for use in web pages & allows them to
do the following:
JavaScript gives HTML designers a programming tool
JavaScript can be used to validate data
JavaScript can read and write HTML elements
Create pop-up windows
Perform mathematical calculations on data
React to events, such as a user rolling over an image or clicking a button
Retrieve the current date and time from a user‟s computer or the last time a document was
modified
Determine the user‟s screen size, browser version, or screen resolution
JavaScript can put dynamic text into an HTML page
JavaScript can be used to create cookies
Advantages of JavaScript:
Less server interaction
Immediate feedback to the visitors
Increased interactivity
Richer interfaces
Web surfers don‟t need a special plug-in to use your
scripts Java Script is relatively secure.
Limitations of JavaScript:
We cannot treat JavaScript as a full-fledged programming language. It lacks some of the
important features like:
Client-side JavaScript does not allow the reading or writing of files. This has been kept for
security reason.
JavaScript cannot be used for networking applications because there is no such support
available.
JavaScript doesn't have any multithreading or multiprocess
capabilities. If your script doesn‟t work then your page is useless.
Points to remember:
1 JavaScript is case-sensitive
2 Each line of code is terminated by a semicolon
VARIABLES
Like any programming language, JavaScript has variables. A variable is a name assigned to
computer memory location to store data. As the name suggests, the value of the variable can
vary, as the program runs. We can create a variable with the var statement:
var <variablename> = <some
value>; Example:
var sum =
0; var str;
We can initialize a variable like this:
str = “hello”;
Rules for variable names:
1# They must begin with a letter, digit or underscore character # We can‟t use spaces in
names
2# Variable names are case sensitive # We can‟t use reserved word as a variable name.
Weakly Typed Language:
Most high-level languages, including C and Java, are strongly typed. That is, a variable must
be declared before it is used, and its type must be included in its declaration. Once a variable is
declared, its type cannot be changed.
As the JavaScript is weakly typed language, data types are not explicitly declared.
Example: var
num; num = 3;
num = "San Diego";
First, when the variable num is declared, it is empty. Its data type is actually the type undefined.
Then we assign it to the number 3, so its data type is numeric. Next we reassign it to the string
"San Diego", so the variable‟s type is now string.
Example:
<html>
<body>
<script language=”javascript” type=”text/javascript”>
var s;
s = “Hello”;
alert(typeof s);
s = 54321;
alert(typeof s);
</script> </body> </html>
Operators in JavaScript
The operators in JavaScript can be classified as follows:
Arithmetic operators
Relational operators
Logical operators
Assignment operators
Note: If the arguments of + are numbers then they are added together. If the arguments are
strings then they are concatenated and result is returned.
Example:
<html>
<body>
<script
language="JavaScript"> <!--
var a = 5;
++a;
alert("The value of a = " +
a ); -->
</script>
</body>
</html>
String (+) Operator:
Example:
txt1="Welcome";
txt2="to L&T Infotech
Ltd.!"; txt3=txt1 + " " + txt2;
(or)
txt1="Welcome ";
txt2="to UCECET.!";
– Looping Statements
– Jumping Statements
2• while loop
3• do-while loop
Example:
<html>
<body>
<script language=“javascript”>
{
Set of
statements }while(
condition);
Jumping Statements:
break statement:
break statement is used to terminate a loop, switch, or label statement.
When we use break without a label, it terminates the innermost enclosing while, do-while, for, or
switch immediately and transfers control to the following statement.
When we use break with a label, it terminates the specified labeled statement
Syntax:
– break;
– break label;
continue statement:
When we use continue without a label, it terminates the current iteration of the innermost
enclosing while, do-while or for statement and continues execution of the loop with the
next iteration.
When we use continue with a label, it applies to the looping statement identified with that label.
Syntax:
– continue;
– continue label;
Ex:
1• var colors = ["Red", "Green", "Blue"];
Note: JavaScript arrays can hold mixed data types as the following example
shows: var a = [“Monday”, 34, 45.7, “Tuesday”];
Accessing Array Elements:
Array elements are accessed through their index. The length property can be used to know the
length of the array. The index value runs from 0 to length-1.
Example:
<script language="javascript">
var a = [1,2,3];
var s = "";
for(var i=0;i<a.length;i++)
{
s += a[i] + " ";
}
alert(s);
</script>
Adding elements to an array:
What happens if we want to add an item to an array which is already full? Many languages
struggle with this problem. But JavaScript has a really good solution: the interpreter
simply extends the array and inserts the new item.
Ex: var a = [“vit”,”svecw”,”sbsp”];
a[3] = “bvrit”;
a[10] = “bvrice”; //this extends the array and the values of elements a[4] to a[9] will
be undefined.
2• Unlike primitive data types, composite types such as arrays and objects are passed by
reference rather than value.
Example:
<html>
<body>
<script language="javascript">
function fun(a,b){
var msg = fun.arguments[0]+".."+fun.arguments[1]; //referring a,b values
alert(msg);
}
try-catch block
The block of code that might cause the exception is placed inside try block. catch block contains
statements that are to be executed when the exception arises.
DOM Hierarchy
The objects in the web page follow a strict hierarchy, where the window object is the very
top level. Because window is the top level “root” object it can be omitted in the address syntax.
For instance, the window.document.bgColor property, which stores the value of the window‟s
current background color, can be addressed simply as document.bgColor
Several of the DOM objects have properties that contain an array of elements in that web
page. For example, with document.images[], the images[] array is a property of the document
object that will store the URL address of each image contained on that web page.The URL of the
first image in the HTML code is stored in the array at document.images[0]
O
B
J
E
C
T
P
R
O
P
E
R
T
I
E
S
:
frames[]
array of frames stored in the order in which they
are defined in the document frames.length
n
u
m
b
e
r
o
f
f
r
a
m
e
s
s
e
l
f
c
u
r
r
e
n
t
w
i
n
d
o
w
o
p
e
n
e
r
the window (if any) which
opened the current window
parent
parent of the current
window if using a
frameset status
m
e
s
s
a
g
e
i
n
t
h
e
s
t
a
t
u
s
b
a
r
d
e
f
a
u
l
t
S
t
a
t
u
s
defaul
t
messa
ge for
the
status
bar
name
the name of the window if it was created using the open( )
method and a name was specified location
this object contains the full URL address of the document that is
currently loaded in the browser, and assigning a new value to this will
load the specified URL into the browser.
A typical URL address may comprise these parts:
Protocol: // host / pathname ? #hash
We can use the following properties of location object to extract
individual pieces of information from URL
window.location.href
window.location.protocol
window.location.host
window.location.pathname
window.location.hash
Example:
<html>
<head>
<title>Date
Object</title> </head>
<body>
<script type="text/javascript">
var d = new Date();
document.write("The Date is: "+d.toString()+"<br>");
document.write("Today date is: "+d.getDate()+"<br>");
document.write("UTC date is: "+d.getUTCDate()+"<br>");
document.write("Minutes: "+d.getMinutes()+"<br>");
document.write("UTC Minutes: "+d.getUTCMinutes()+"<br>");
15 atan(value)
Form elements:
The elements of the form are held in the array window.document.forms[].elements[] The
properties of the form elements can be accessed and set using Javascript.
The elements of the form are held in the array window.document.forms[].elements[] The
properties of the form elements can be accessed and set using Javascript.
2 A cookie is a small piece of information that is passed back and forth in the HTTP
request and response. The cookie sent by a servlet to the client will be passed back to
the server when the client requests another page from the same application.
3 Cookies are tiny files that can be written by javascript to store small amounts of data on
the local hard drive. There are limitations to the use of cookies that restrict their size to 4
kilobytes and web browsers are not required to retain more than 20 cookies per web
server. Typically a cookie may often retain user data for use across web pages or on
subsequent visits to a web site
4 Depending on the maximum age of a cookie, the Web browser either maintains the
cookie for the duration of the browsing session (i.e., until the user closes the Web
browser) or stores the cookie on the client computer for future use. When the browser
requests a resource from a server, cookies previously sent to the client by that server
are returned to the server as part of the request formulated by the browser. Cookies are
deleted automatically when they expire (i.e., reach their maximum age).
Benefits of Cookies:
1 Identifying a user during an e-commerce session
4 Focusing advertising: Cookies let the site remember which topics interest certain users
and show advertisements relevant to those interests.
History:
Cookies were originally invented by Netscape to give 'memory' to web servers and browsers.
The HTTP protocol, which arranges for the transfer of web pages to your browser and browser
requests for pages to servers, is state-less, which means that once the server has sent a page to a
browser requesting it, it doesn't remember a thing about it. So if you come to the same web page
a second, third, hundredth or millionth time, the server once again considers it the very first
time you ever came there.
This can be annoying in a number of ways. The server cannot remember if you identified
yourself when you want to access protected pages, it cannot remember your user preferences,
it cannot remember anything. As soon as personalization was invented, this became a major
problem.
Cookies were invented to solve this problem. There are other ways to solve it, but cookies
are easy to maintain and very versatile.
As soon as you request a page from a server (which was requested earlier & the server sent
cookie to the client), the cookie is added to the HTTP header. Server side programs can then read
out the information and give response accordingly. So every time you visit the site the cookie
comes from, information about you is available. This is very nice sometimes, at other times it
may somewhat endanger your privacy.
Cookies can be read by JavaScript too. They're mostly used for storing user
preferences. name-value
Each cookie has a name-value pair that contains the actual information. The name of the cookie is
for your benefit, you will search for this name when reading out the cookie information.
Expiry date
Each cookie has an expiry date after which it is trashed. If you don't specify the expiry date
the cookie is trashed when you close the browser. This expiry date should be in UTC
(Greenwich) time.
Domain and path
Each cookie also has a domain and a path. The domain tells the browser to which domain
the cookie should be sent. If you don't specify it, it becomes the domain of the page that sets
the cookie.
document.cookie
Cookies can be created, read and erased by JavaScript. They are accessible through the property
document.cookie. Though you can treat document.cookie as if it's a string, it isn't really, and you
have only access to the name-value pairs.
Handling Events
There are two ways to set and execute the JavaScript event handler for an HTML tag:
– Set the event handler property inside HTML
Example:
<html>
<head>
<script language="javascript">
function change(v)
2• For example, the pattern /abc/ matches character combinations in strings only when
exactly the characters 'abc' occur together and in that order.
2• There is no match in the string "Grab crab" because it does not contain the substring
'abc'.
2• For example, the pattern /ab*c/ matches any character combination in which a single
'a' is followed by zero or more 'b's (* means 0 or more occurrences of the preceding item)
and then immediately followed by 'c'. In the string "cbbabbbbcdebc," the pattern matches the
substring 'abbbbc'
Regular expression patterns in java script must begin and end with forward slashes.
^ circumflex operator
\w Alphanumeric
character \D Alphabetic
characters
\d Numeric chacters
\d [0-9] A digit
\D [^0-9] Not a digit
\w [A-Za-z_0-9] A word character(Alphanumeric)
\W [^A-Za-z_0-9] Not a word character
\s [\r\t\n\f] A white space character
\S [^\r\t\n\f] Not a White space character