Javascript Unit2 PDF
Javascript Unit2 PDF
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:
JavaScript is case-sensitive
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:
# They must begin with a letter, digit or underscore character # We can‟t use spaces in names
# 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 CMRCET.!";
Conditional Operator: Conditional operator is one the JavaScript‟s comparison operator, which
assigns a value to a variable based on some condition.
Syntax :
variablename=(condition)? value1 : value2;
Logical operators: Logical operators are used to combine two or more conditions.
– Looping Statements
– Jumping Statements
• while loop
• do-while loop
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:
• 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.
• Unlike primitive data types, composite types such as arrays and objects are passed by reference
rather than value.
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]
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>");
Number Square
1 1
2 4
3 9
<html>
<body>
<table border=1>
<tr> <th>Number <th>Square </tr>
<script language="javascript">
var n = prompt("enter n");
for(i=1;i<=n;i++)
{
document.write("<tr><td>"+i+"<td>"+(i*i)+"</tr>");
}
</script>
</table>
</body>
</html>
FORM OBJECT
The window.document.forms object contains an array of all the forms in a HTML document,
indexed in the order in which they appear in the HTML code.
For example, window.document.forms[0] addresses the first form to appear in the HTML code
of a web page.
If the id attribute of the <form> element has been assigned a value, then the form can be
addressed by name.
For example, a form named reg can be addressed as document.forms.reg
All the attributes assigned in the <form> tag can be accessed as properties of that form object.
Example:
<html>
<head>
<script language=”javascript”>
window.onload = fun;
function fun()
{
var msg = “Form name: “ + document.forms.reg.id;
msg += “\nMethod: “ + document.forms.reg.method;
msg += “\nAction: “ + document.forms.reg.action;
window.alert(msg);
}
</script>
</head>
<body>
<form id=”reg” method=”post” action=mailto:[email protected]>
Name: <input type="text" size=10> <br>
Age: <input type="text" size=5> <br>
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.
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
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:
Identifying a user during an e-commerce session
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)
• For example, the pattern /abc/ matches character combinations in strings only when exactly the
characters 'abc' occur together and in that order.
• There is no match in the string "Grab crab" because it does not contain the substring 'abc'.
• 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