Unit III BSC Javascript Css
Unit III BSC Javascript Css
UNIT – III
Introduction to JavaScript
What is DHTML, JavaScript, basics, variables, string manipulations, mathematical functions, statements,
operators, arrays, functions.
Objects in JavaScript: Data and objects in JavaScript, regular expressions, exception handling
………………………………………………………………………………………………………………………….
1.What is DHTML?
Dynamic HTML, or DHTML, is an umbrella term for a collection of technologies used together to create
interactive and animated websites by using a combination of a static markup language (such as HTML), a
client-side scripting language (such as JavaScript), a presentation definition language (such as CSS), and the
Document Object Model (DOM). The application of DHTML was introduced by Microsoft with the
release of Internet Explorer 4 in 1997.
HTML does not require any processing from browser, while DHTML requires processing from
browser which changes its look and feel.
2. JavaScript
A JavaScript is a scripting language used at the client side design along with HTML,CSS, and XML. The
main use of JavaScript is to validate the data present in a web application. One can also control the web
application using JavaScript.
Example: For example, when your login into a Facebook page account you need to provide correct user
name and password. If anything went wrong it display an error message. That means someone at the
background validating the username and password. This type of validation can be done using JavaScript.
Benefits / Advantages of JavaScript
JavaScript has a number of big benefits to anyone who wants to make their website dynamic.
It is widely supported in web browsers
It gives easy access to the document object and can manipulate most of them.
JavaScript can give interesting animations without the long download times associated with many
multimedia data types.
Web servers don’t need a special plugin to your scripts.
JavaScript is relatively easy.
Problems with Java Script
Most scripts relay upon manipulating the elements of the DOM. Support for standard set of objects
currently does not exist and access to objects differs from browser to browser.
If your script does not work then your page is useless.
Because of the problem of broken scripts many web pages suffers disable JavaScript support in their
browsers.
Scripts can run slowly and complex scripts can take a long time to startup.
Note
Plugin: plugin is small application which handle specific data type and which may either run as
standard alone application or embedded within the browser.
3. JavaScript Basic
<h2>JavaScript in Head</h2>
</body>
</html>
</body>
</html>
If we use a lot of scripts or our scripts are complex then including the code inside the webpage will
make your source file difficult to read and debug. We can put JavaScript code in a separate file and
include the code in the head of the webpage. JavaScript programs are stored in files with the .js extension.
myScript.js
function myFunction() {
document.getElementById("demo").innerHTML = "Paragraph changed.";
}
To use an external script, put the name of the script file in the src (source) attribute of a <script> tag:
<script src="myScript.js"></script>
Example:
<!DOCTYPE html>
<html>
<body>
<h2>External JavaScript</h2>
<p id="demo">A Paragraph.</p>
<button type="button" onclick="myFunction()">Try it</button>
<p>(myFunction is stored in an external file called "myScript.js")</p>
<script src="myScript.js"></script>
</body>
</html>
Input: In JavaScript the input is get by using prompt box. This function frames a window object and
its general form is
Output: In JavaScript t he data can be displayed on the web page by using two functions: write() and
writeln(). The general form is
1. Numerical data types: These are the basic numbers it can include all the integers, fractions and
expression data.
2. String data type: These are collection of characters or a single character in the double quotes. The string
data type can also store numbers represented in the form of string using double quotes.
3. Boolean data type: Boolean variables hold the values “ true” and “false”. These are used a lot in
programming to hold results of conditional text.
4. Null data types: This is used when you don’t know something. A Null value means one that has been
decided.
d) Alternatives to JavaScript:
There are so many alternative solutions to the problem of making websites interactive and dynamic.
Some of these rely upon complex multimedia data, while others are script based. Some of the scripting
solutions which might be consider as competitors to JavaScript are listed below.
Perl: A complex language that is commonly used for server side CGI scripting. Perl is available for client
side work through a subset called PerlScript which can also be used when writing active server pages.
VBScript: widely used but unfortunately platform specific. This language is only available under the
Microsoft windows operating system.
Python: A little known languages that is making inroads into the CGI writing area. A web browser has
been written in Python which can run Python applets.
TCL: This has been a popular choice for systems programming. The language itself has been widely
criticised by proponents of other scripting languages but it is clearly effective in its own niche.
Java: This is a scripting language but it is used for many of the same things as JavaScript. It’s very good at
menus and data validation on the client but can be very slow.
4. Variables in JavaScript
Like any programming languages JavaScript has variables. These are data items that you can manipulate
as program the program runs. A variable is a named value that you use in your program.
Creating variables:
The variable declaration tells what type of data we are using in your JavaScript. Like other languages
JavaScript also provides variables. When you declare a variable we can’t use its type instead JavaScript use
“var” keyword to create variables. This keyword is placed before the variable name.
Example: var a;
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Variables</h2>
<p>In this example, x, y, and z are variables.</p>
<p id="demo"></p>
<script>
var x = 5;
var y = 6;
var z = x + y;
document.getElementById("demo").innerHTML =
"The value of z is: " + z;
</script>
</body>
</html>
A sting is collection of characters. The sting object is used to manipulate a stored piece of text, String
objects are created as,
Or
JavaScript has functions which perform different operations on stings such as string comparison, searching
a string in another string, converting from one case to another one.
The indexOf() method returns the index of (the position of) the first occurrence of a specified text in
a string.
Example: s1
h e l l o
0 1 2 3 4
Var s1=”hello”;
indexOf(l);
In the above example, the indexOf() returns index position 2.
The lastIndexOf() method returns the index of the last occurrence of a specified text in a string.
substring(start, end)
substr(start, length)
slice() extracts a part of a string and returns the extracted part in a new string.
The method takes 2 parameters: the start position, and the end position (end not included).
This example slices out a portion of a string from position 7 to position 12 (13-1):
Example:
Example:
Example:
var str = "Apple, Banana, Kiwi";
var res = str.slice(7, 6);
The replace() method replaces a specified value with another value in a string.
Example:
str = "Please visit Microsoft!";
var n = str.replace("Microsoft", "W3Schools");
The replace() method does not change the string it is called on. It returns a new string.
By default, the replace() method replaces only the first match.
By default, the replace() method is case sensitive.
Example:
Example:
7. String.trim()
Note:
All string methods return a new string. They don't modify the original string.
Formally said: Strings are immutable: Strings cannot be changed, only replaced.
7. Statements in JavaScript
JavaScript supports three types of statements branching statements, looping statements, jumping
statements.
i) Branching statements
The conditional branching statements help to
jump from one part of the program to another
depending on whether a particular condition is satisfied
or not. Generally they are two types of branching
statements.
a) if-else statement:
Whenever you want to test the truth of a
condition before executing any more of your program,
use this construct. This statement means that if some
condition is true then do one thing, if the condition is
false do another.
Syntax:
If(condition{
// do some thing
}
else
{
// do another
}
Example program:
<html>
<head>
<title>IF Statments!!!</title>
<script type="text/javascript">
var age = prompt("Please enter your age");
if(age>=18)
document.write("You are an adult <br />");
if(age<18)
document.write("You are NOT an adult <br />");
</script>
</head>
<body>
</body>
</html>
b) Switch statement
The switch statement is used to perform different actions based on different conditions. JavaScript Use
the switch statement to select one of many code blocks to be executed.
Syntax:
switch(expression) {
case x:
// code block
break;
case y:
// code block
break;
default:
// code block
}
This is how it works:
The switch expression is evaluated once.
The value of the expression is compared with the values of each case.
If there is a match, the associated block of code is executed.
Example:
<!DOCTYPE html>
<html>
<body>
<p id="demo"></p>
<script>
var day;
switch (new Date().getDay()) {
case 0:
day = "Sunday";
break;
case 1:
day = "Monday";
break;
case 2:
day = "Tuesday";
break;
case 3:
day = "Wednesday";
break;
case 4:
day = "Thursday";
break;
case 5:
day = "Friday";
break;
case 6:
day = "Saturday";
}
document.getElementById("demo").innerHTML = "Today is " + day;
</script>
</body>
</html>
2. Looping statements
Loops are handy, if you want to run the same code over and over again, each time with a different value.
Often this is the case when working with arrays; Instead of assigning each value using index, we read and
print values using loops.
JavaScript supports different kinds of loops:
for - loops through a block of code a number of times
do-while: - also loops through a block of code while a specified condition is true
a) for loop:
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Loops</h2>
<p id="demo"></p>
<script>
var text = "";
var i;
for (i = 0; i < 5; i++) {
text += "The number is " + i + "<br>";
}
document.getElementById("demo").innerHTML = text;
</script>
</body>
</html>
b) for-in: The JavaScript for/in statement loops through the properties of an object:
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Loops</h2>
<p>The for/in statement loops through the properties of an object.</p>
<p id="demo"></p>
<script>
var txt = "";
var person = {fname:"John", lname:"Doe", age:25};
var x;
for (x in person) {
txt += person[x] + " ";
}
document.getElementById("demo").innerHTML = txt;
</script>
</body>
</html>
c) While statement
The while loop loops through a block of code as long as a specified condition is true.
Syntax:
while (condition) {
// code block to be executed
}
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript while</h2>
<p id="demo"></p>
<script>
var text = "";
var i = 0;
while (i < 10) {
text += "<br>The number is " + i;
i++;
}
document.getElementById("demo").innerHTML = text;
</script>
</body>
</html>
d) do-wile statement
The do-while loop is a variant of the while loop. This loop will execute the code block once, before
checking if the condition is true, and then it will repeat the loop as long as the condition is true.
Syntax:
do {
// code block to be executed
}while (condition);
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript do ... while</h2>
<p id="demo"></p>
<script>
var text = ""
var i = 0;
do {
text += "<br>The number is " + i;
i++;
}while (i < 10);
document.getElementById("demo").innerHTML = text;
</script>
</body>
</html>
3. Jumping statements
The break statement "jumps out" of a loop. The continue statement "jumps over" one iteration in the loop.
The Break Statement
You have already seen the break statement used in an earlier chapter of this tutorial. It was used to "jump
out" of a switch() statement.
The break statement can also be used to jump out of a loop.
The break statement breaks the loop and continues executing the code after the loop (if any):
<!DOCTYPE html>
<html>
<body>
<p>A loop with a break.</p>
<p id="demo"></p>
<script>
var text = "";
var i;
for (i = 0; i < 10; i++) {
if (i === 3)
{
break;
}
text += "The number is " + i + "<br>";
}
document.getElementById("demo").innerHTML = text;
</script>
</body>
</html>
8. Operators in JavaScript:
9. Arrays in JavaScript
An array is an ordered set of data elements which can be accessed through a single name. Like other
languages arrays in JavaScript store group of elements but of different types. In JavaScript an array is an
object and you have different methods for performing different operations.
There is no relationship in between the elements which are stored in JavaScript arrays. Then we can define
an array in JavaScript is a collection of non-homogenous elements under a single name. The index value
or the subscript value is used to perform any operations on an array. The for loop is most frequently used
loop along with arrays.
The basic operations that are performed on arrays are creation, adding of elements, accessing individual
elements, searching an array, removing array elements.
a) Creating arrays:
When we add an element to the already filled array, the interpreter simply extend the array and inserts
the new item.
The elements in the array are accessed through their index. The same access method is used to find the
elements and to change their value. When accessing array elements you don’t want to read beyond its
end. Therefore, you need to know how many elements have been stored. This is done through the length
attribute.
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Arrays</h2>
<p>JavaScript array elements are accessed using numeric indexes (starting from 0).</p>
<p id="demo"></p>
<script>
var cars = ["Saab", "Volvo", "BMW"];
document.getElementById("demo").innerHTML = cars;
</script>
</body>
</html>
d) Searching an array.
To search an array, simply read each element in turn and compare it with the value that you are looking
for. The following snapshot code shows how to search an array.
for(var i-0;i<length;i++)
{
If(data[i]=”Tuesday”)
{
document. Writeln (data[i]+”,”);
break;
}
}
e) Removing an array element
Removing elements from an array is quite string forward. JavaScript does not provide a built in function
to do this for you. To remove an element for yourself use the following procedure.
Read each element in the array
If the element is not the one you want to delete, copy it into a temporary array.
If you want to delete the element do nothing.
Increment the loop counter.
Repeat the process.
<html>
<head>
<title> removing an element </title>
</head>
<Script type=”text/JavaScript”>
<!-------------
document.writeln(“<h1> removing an element from array</h1>);
var data=[“monda”,” Tuesday”,34,76.46,”Wednesday”];
document.writeln(“<p>”);
var len=data.length;
for(i=0;i<len;i++)
{
document.writeln(data[i]+”,”);
}
document.writeln(“</p>”);
var rem=window.prompt(“which element you want to remove”);
var tem=new Array(data.length-1);
var j=0;
for(i=0;i<n;i++)
{
if(data[i]=rem)
{
// nothing to do
}
else
{
temp[j]=data[i];
j++;
}
}
data=temp;
var len=data.length;
for(var i=0;i<length;i++)
{
document.writeln(data[i]+”,”);
}
//-------->
</script>
</body>
</head>
3. pop(): This method is used to delete an element from the array and it reduces size of array.
4. push(element1,element2): add a list of items to an array and it increases the size of the array.
5. reverse(): It reversers all the elements in the array, so that it follows last in first out process.
6. shift(): Remove one element from the array and it is the first element of an array.
7. slice(start, finish): It is used to extract a range of elements from an array from the start of index to finish
of the index. It works similarly as substr().
8.sort(): the array elements are sorted in index order.
9. slice(index,element1,element2,…..): It removes specified element in the array index and all the
remaining elements can form new array.
10. shift():The shift() method removes the first array element and "shifts" all other elements to a lower
index.
11. unshift(): The unshift() method adds a new element to an array (at the beginning), and "unshifts" older
elements.
------------------
10. Functions in JavaScript
A JavaScript function is a block of code designed to perform a particular task. A JavaScript function is
executed when "something" invokes it (calls it). JavaScript has a lot of built in functions into the language.
a) Defining functions
you can create your own function using the following syntax
Function parameters are listed inside the parentheses () in the function definition.
Function arguments are the values received by the function when it is invoked.
Inside the function, the arguments (the parameters) behave as local variables.
Advantages:
Function reduces the complexity of the program
The repeated code is eliminated by using function call
Functions are basic building blocks of any programming language.
b) Passing parameters
Not every function accepts parameters, not all values have to be passed as parameters. When a
function receives a value as parameter, the value is given a name and can be accessed using that name by
the function. The names of parameters are taken from the function definition and are applied in the order
in which parameters are passed in.
<html>
<body>
<h2>JavaScript Functions</h2>
<p>This example calls a function which performs a calculation and returns the result:</p>
<script>
var x = myFunction(4, 3); // function call
document.writeln(x);
function myFunction(a, b)
{
return a * b;
}
</script>
</body>
</html>
Output:
Javascript Functions
This example calls a function which performs a calculation and returns the result:
12
d) Returning values
When JavaScript reaches a return statement, the function will stop executing.
If the function was invoked from a statement, JavaScript will "return" to execute the code after the
invoking statement.
Functions often compute a return value. The return value is "returned" back to the "caller":
<html>
<body>
<h2>JavaScript Functions</h2>
<p>This example calls a function which performs a calculation and returns the result:</p>
<script>
var x = myFunction(4, 3); // function call
document.writeln(x);
function myFunction(a, b)
{
return a * b;
}
</script>
</body>
</html
e) Scoping Rules
A scope rule determines how a variable can be accessed. JavaScript variables can be either local or global.
global scope: global scope means that a variable is available to all parts of the program. such variables are
declared outside of any function and are usually used to hold static data that we won’t alter once it has
been created.
local scoping: local variables are declared inside a function. They can only be used by that function. If you
want the value associated with a local variable to the available to other functions then you must pass it as
parameter.
<html>
<body>
<h2>JavaScript Functions</h2>
<p>Outside myFunction() carName is undefined.</p>
<p id="demo1"></p>
<p id="demo2"></p>
<script>
myFunction();
function myFunction() {
var carName = "Volvo";
document.getElementById("demo1").innerHTML =
typeof carName + " " + carName;
}
document.getElementById("demo2").innerHTML =
typeof carName;
</script>
</body>
</html
Objects in JavaScript
Data and objects in JavaScript, regular expressions, exception handling, built-in objects, events.
………………………………………………………………………………………………………………………….
An object is a thing. It can be anything that you like from. Some data through a set of methods to an
entire system. The reason that object orientation is such a powerful idea is that quite simply it lets software
designer and developers mimic the real world designs.
Objects are described in software and design constructs called classes. A class usually contains some data
items and some methods. Each class provides services to other classes in the system. A single generic class
can be specialized in many ways and each of the specialized versions inherits. Some of the properties and
behaves of the generic class. That means that common parts of the program can be developed just once
and easily reused.
An object is a run time instance of a class. The object has all of the behavior that was defined in the class
and is able to perform processing.
JavaScript Objects: The built in JavaScript objects such as document and window act, and are used, like
standard OO object. JavaScript diverges from traditional OO is in its treatment of user defined objects. An
object is really a data structure that has been associated with some functions. It doesn’t have inheritance
and the structure of the code can look a little peculiar.
<html>
<head>
<script language=”JavaScript”>
<!..........
function objDemo()
{
popup(“Hello”);
myhouse =new house(“ Dream hone”,2,4);
alert(“myhouse.name+”has”+myhouse.floors+”floors and”+myhouse.rooms()+”Rooms”);
myhouse.leave(“farewell”);
}
function frooms()
{
var groundfloor=3;
var utilities=2;
var total=0;
if(this.floors<=0)
{
total=0;
}
else
{
if(this.floors==1)
{
total = this.bedrooms+utilities;
}
else
{
total=(this.floors*utilities);
total+=groundfoloor;
total+=this.bedrooms;
}
}
return total;
}
function popup(msg)
{
alert(msg);
}
//----->
</script>
</head>
<body onLoad==objDemo”>
</body>
</html>
New Keyword: The new keyword is used to create objects. It allocates memory and storage for them and
sets all variables that can be set at this stage.
This keyword: to differentiate between global variables and those which are part of an object but may
have same name, JavaScript uses this keyword. Whenever you refer to a variable which is a part of an
object you must precede the variable name by this keyword.
.(dot) operator: when referring to a property of an object, where a method or a variable, a dot is placed
between the object name and the property.
Regular expressions are used to perform pattern-matching and "search-and-replace" functions on text.
Syntax:
/pattern/modifiers;
Example:
When you search for data in a text, you can use this search pattern to describe what you are
searching for.
Regular expressions can be used to perform all types of text search and texts replace operations.
Dynamic patterns are created using new keyword to create an instance of the RegExp class;
Method Descript
Compile() Changes the regular expression
Exec() Search a string for specified value.
Test() Search a string for s specified value.
Method Description
Search() Search a string for specified value. Returns the position of the value
Match() Search a string for a specified value. Returns an array of the found values.
Replace() Replace characters with other characters
Split() Split a string into an array of strings
Modifier Description
i Performs case sensitive matching
g Performs a global matching. Find all matches, do not stop after the first match.
m Perform multiline matching.
Expression Description
[abc] Find any of the characters between the brackets
[0-9] Find any of the digits between the brackets
(x|y) Find any of the alternatives separated with |
Example:
<html>
<head>
<title> pattern matching </title>
</head>
<body>
<script language=”JavaScript”>
<!--------
var msg=prompt(“ enter the text”,” “);
var hunt=prompt(“enter regular expression”, “”);
var re=new RegExp(hunt);
var result=re.exec(msg);
document.writeln(“<h1> search result</h1><p>”);
if(result)
{
document.write(“ found”,+result[0]);
}
else
{
document.write(“not found”);
}
documtn.writeln(“</p>”);
document.close();
//--->
</script>
</body>
</html>
Run time error handling is very important in all programs. Your program should never fall over or stop
just because a user enters invalid data or does something unexpected. May object oriented programming
languages provide a mechanism for dealing with general classes of errors. This mechanism is called
exception handling.
An exception is an object based programming object, created dynamically at run time which encapsulates
an error and some information about it.
The latest versions of JavaScript added exception handling capabilities. JavaScript implements the
try...catch...finally construct as well as the throw operator to handle exceptions.
The try statement lets you test a block of code for errors.
The catch statement lets you handle the error.
The throw statement lets you create custom errors.
The finally statement lets you execute code, after try and catch, regardless of the result.
Example:
<html>
<head>
<script type = "text/javascript">
<!--
function myFunc() {
var a = 100;
var b = 0;
try {
if ( b == 0 ) {
throw( "Divide by zero error." );
} else {
var c = a / b;
}
}
catch ( e ) {
alert("Error: " + e );
}
}
//-->
</script>
</head>
<body>
<p>Click the following to see the result:</p>
<form>
<input type = "button" value = "Click Me" onclick = "myFunc();" />
</form>
</body>
</html>
HTML Events
An HTML event can be something the browser does, or something a user does.
Here are some examples of HTML events:
An HTML web page has finished loading
An HTML input field was changed
An HTML button was clicked
Often, when events happen, you may want to do something.
JavaScript lets you execute code when events are detected.
HTML allows event handler attributes, with JavaScript code, to be added to HTML elements.
Example
<!DOCTYPE html>
<html>
<body>
<button onclick="document.getElementById('demo').innerHTML=Date()">The time is?</button>
<p id="demo"></p>
</body>
</html>
JavaScript is an event driven system
JavaScript is an event driven system. Nothing happens unless it is initiated by an event outside the script.
An event is any change that the user makes to the state of the browser. Our script can be initiated when
the page loads and then run automatically. Generally we add a script to a page to improve its
functionality or appearance. The script is an integral part of the page but its operation should always be
controlled by the user.
Examples of using JavaScript to react to events
A document is a web page that is being either displayed or created. The document has a number of
properties that can be accessed by JavaScript programs and used to manipulate the content of the page.
Write or writeln Html pages can be created using JavaScript. This is done by using the write or writeln
methods of the document object.
Document.write(“<h1> Hello </h1>”);
Two aspects of the form can be manipulated through JavaScript. First, most commonly and probably most
usefully, the data that is entered onto your form can be checked at submission. Second you can actually
build forms through JavaScript.
<html>
<head>
<script language="javascript">
function fibbo()
{ var a=0,b=1,c,i=1;
var op=a+" ,"+b+" ,";
var num=window.prompt("Enter the Number:",1);
for(i=1;i<=num;i++)
{
c=a+b;
a=b;
b=c;
op+=c+" ,";
}
document.getElementById("num").innerHTML="Series is "+op;
}
</script>
</head>
<body>
<form name="f1">
<table border=2>
<tr>
<td>
<input type=button value="Fibonacci" onclick="fibbo()">
</td>
<td id="num">result</td>
</tr>
</table>
</form>
</body>
</html>
No two browsers models will process your script in the same way. It is important that you try to find out
which browser is being used to view your page. You can then make a choice for your visitors.
5. String Object
6. Math Object