WIDT UNIT-III
WIDT UNIT-III
WIDT UNIT-III
1) What is JavaScript ?
Javascript is a dynamic computer programming language. It is lightweight and most
commonly used as a part of web pages, whose implementations allow client-side script to
interact with the user and make dynamic pages. It is an interpreted programming language
with object-oriented capabilities.
JavaScript was first known as LiveScript, but Netscape changed its name to JavaScript,
possibly because of the excitement being generated by Java. JavaScript made its first
appearance in Netscape 2.0Brendan Eich in 1995, in 1995 with the name LiveScript. The
general-purpose core of the language has been embedded in Netscape, Internet Explorer,
and other web browsers.
Features of JavaScript
1. All popular web browsers support JavaScript as they provide built-in execution
environments.
2. JavaScript follows the syntax and structure of the C programming language. Thus,
it is a structured programming language.
3. JavaScript is a weakly typed language, where certain types are implicitly cast
(depending on the operation).
4. JavaScript is an object-oriented programming language that uses prototypes
rather than using classes for inheritance.
5. It is a light-weighted and interpreted language.
6. It is a case-sensitive language.
7. JavaScript is supportable in several operating systems including, Windows,
macOS, etc.
8. It provides good control to the users over the web browsers.
<script>... </script>:
JavaScript can be implemented using JavaScript statements that are placed within the
<script>... </script>.
You can place the <script> tags, containing your JavaScript, anywhere within your web
page, but it is normally recommended that you should keep it within the <head> tags.
The <script> tag alerts the browser program to start interpreting all the text between
these tags as a script. A simple syntax of your JavaScript will appear as follows.
<script ...>
JavaScript code
</script>
Language − This attribute specifies what scripting language you are using.
Typically, its value will be javascript. Although recent versions of HTML (and
XHTML, its successor) have phased out the use of this attribute.
Type − This attribute is what is now recommended to indicate the scripting
language in use and its value should be set to "text/javascript".
JavaScript in <body>...</body> section If you need a script to run as the page loads so that the
script generates content in the page, then the script goes in the <body> portion of the document. In
this case, you would not have any function defined using JavaScript. Take a look at the following code.
<html>
<head>
</head>
<body>
<script type="text/javascript">
<!--
document.write("Hello World")
//-->
</script>
<p>This is web page body </p>
</body>
</html>
JavaScript in <body> and <head> Sections
You can put your JavaScript code in <head> and <body> section altogether as follows
<html>
<head>
<script type="text/javascript">
<!--
function sayHello() {
alert("Hello World")
}
//-->
</script>
</head>
<body>
<script type="text/javascript">
<!--
document.write("Hello World")
//-->
</script>
<input type="button" value="Say Hello" />
</body>
</html>
JavaScript in External File
As you begin to work more extensively with JavaScript, you will be likely to find that
there are cases where you are reusing identical JavaScript code on multiple pages of a
site.
You are not restricted to be maintaining identical code in multiple HTML files. The script
tag provides a mechanism to allow you to store JavaScript in an external file and then
include it into your HTML files.
Here is an example to show how you can include an external JavaScript file in your HTML
code using script tag and its src attribute.
<html>
<head>
<script type="text/javascript" src="filename.js" ></script>
</head>
<body>
.......
</body>
</html>
To use JavaScript from an external file source, you need to write all your JavaScript
source code in a simple text file with the extension ".js" and then include that file as
shown above.
For example, you can keep the following content in filename.js file and then you can
use sayHello function in your HTML file after including the filename.js file.
function sayHello() {
alert("Hello World")
}
JavaScript is a dynamic type language, means you don't need to specify type of the
variable because it is dynamically used by JavaScript engine. You need to use var here
to specify the data type. It can hold any type of values such as numbers, strings etc. For
example:
3) JavaScript Variables
Like many other programming languages, JavaScript has variables. Variables can be
thought of as named containers. You can place data into these containers and then refer
to the data simply by naming the container.
Before you use a variable in a JavaScript program, you must declare it. Variables are
declared with the var keyword as follows.
<script type="text/javascript">
<!--
var money;
var name;
//-->
</script>
1. Name must start with a letter (a to z or A to Z), underscore( _ ), or dollar( $ )
sign.
2. After first letter we can use digits (0 to 9), for example value1.
3. JavaScript variables are case sensitive, for example x and X are different variables.
<script>
function abc(){
var x=10;//local variable
}
</script>
JavaScript global variable
A JavaScript global variable is accessible from any function. A variable i.e. declared
outside the function or declared with window object is known as global variable. For
example:
<script>
var data=200;//gloabal variable
function a(){
document.writeln(data);
}
function b(){
document.writeln(data);
}
a();//calling JavaScript function
b();
</script>
4)JavaScript Operators
JavaScript operators are symbols that are used to perform operations on operands. For
example:
1. var sum=10+20;
1. Arithmetic Operators
2. Comparison (Relational) Operators
3. Bitwise Operators
4. Logical Operators
5. Assignment Operators
6. Special Operators
Arithmetic operators are used to perform arithmetic operations on the operands. The
following operators are known as JavaScript arithmetic operators.
Operator Description Example
+ Addition 10+20 = 30
- Subtraction 20-10 = 10
/ Division 20/10 = 2
% Modulus 20%10 = 0
(Remainder)
The JavaScript comparison operator compares the two operands. The comparison
operators are as follows:
The bitwise operators perform bitwise operations on operands. The bitwise operators
are as follows:
= Assign 10+10 = 20
Operator Description
(?:) Conditional Operator returns value based on the condition. It is like if-
else.
Thus, you refer to the constant pi as Math.PI and you call the sine function as
Math.sin(x), where x is the method's argument.
Syntax
The syntax to call the properties and methods of Math are as follows
Math Methods
Here is a list of the methods associated with Math object and their description
abs()
1
Returns the absolute value of a number.
acos()
2
Returns the arccosine (in radians) of a number.
asin()
3
Returns the arcsine (in radians) of a number.
atan()
4
Returns the arctangent (in radians) of a number.
atan2()
5
Returns the arctangent of the quotient of its arguments.
ceil()
6
Returns the smallest integer greater than or equal to a number.
cos()
7
Returns the cosine of a number.
exp()
8
Returns EN, where N is the argument, and E is Euler's constant, the base of the
natural logarithm.
floor()
9
Returns the largest integer less than or equal to a number.
log()
10
Returns the natural logarithm (base E) of a number.
max()
11
Returns the largest of zero or more numbers.
min()
12
Returns the smallest of zero or more numbers.
pow()
13
Returns base to the exponent power, that is, base exponent.
random()
14
Returns a pseudo-random number between 0 and 1.
round()
15
Returns the value of a number rounded to the nearest integer.
sin()
16
Returns the sine of a number.
sqrt()
17
Returns the square root of a number.
tan()
18
Returns the tangent of a number.
<html>
<head>
<title>
JavaScript Math Object
</title>
</head>
<body>
<h2>JavaScript Math Object</h2>
</html>
6)JavaScript String
The JavaScript string is an object that represents a sequence of characters.
1. By string literal
2. By string object (using new keyword)
1) By string literal
The string literal is created using double quotes. The syntax of creating string using
string literal is given below:
<script>
var str="This is string literal";
document.write(str);
</script>
2) By string object (using new keyword)
The syntax of creating string object using new keyword is given below:
Methods Description
indexOf() It provides the position of a char value present in the given string.
lastIndexOf() It provides the position of a char value present in the given string by
searching a character from the last position.
substr() It is used to fetch the part of the given string on the basis of the
specified starting position and length.
substring() It is used to fetch the part of the given string on the basis of the
specified index.
slice() It is used to fetch the part of the given string. It allows us to assign
positive as well negative index.
toLocaleUpperCase() It converts the given string into uppercase letter on the basis of host?s
current locale.
split() It splits a string into substring array, then returns that newly created
array.
trim() It trims the white space from the left and right side of the string.
<html>
<head>
<title>STRINGS METHODS</title>
</head>
<body>
<script>
var str="javascript";
document.write(str.charAt(2));
var s1="javascript ";
var s2="concat example";
var s3=s1.concat(s2);
document.write(s3);
var s1="javascript from javatpoint indexof";
var n=s1.indexOf("from");
document.write(n);
var s1="javascript from javatpoint indexof";
var n=s1.lastIndexOf("java");
document.write(n);
var s1="JavaScript toLowerCase Example";
var s2=s1.toLowerCase();
document.write(s2);
var s1="JavaScript toUpperCase Example";
var s2=s1.toUpperCase();
document.write(s2);
var s1="abcdefgh";
var s2=s1.slice(2,5);
document.write(s2);
var s1=" javascript trim ";
var s2=s1.trim();
document.write(s2);
</script>
</body>
</html>
7)Array:
An array is a special variable, which can hold more than one value at a time.
An array can hold many values under a single name, and we can access the values by
referring to an index number.
Creating an Array
Syntax:
Example
The following example also creates an Array, and assigns values to it:
Example
cars[0] = "Opel";
Methods
pop():
Javascript array pop() method removes the last element from an array and returns that
element.
Syntax
array.pop();
Return Value
<script type="text/javascript">
</script>
push():
Javascript array push() method appends the given element(s) in the last of the array
and returns the length of the new array.
Syntax
Parameter Details
element1, ..., elementN: The elements to add to the end of the array.
Return Value
<script type="text/javascript">
</script>
shift():
Javascript array shift()method removes the first element from an array and returns that
element.
Syntax
array.shift();
Return Value
unshift():
Javascript array unshift() method adds one or more elements to the beginning of an
array and returns the new length of the array.
Syntax
Parameter Details
element1, ..., elementN − The elements to add to the front of the array.
Return Value
splice():
Javascript array splice() method changes the content of an array, adding new elements
while removing old elements.
Syntax
Parameter Details
element1, ..., elementN − The elements to add to the array. If you don't specify any
elements, splice simply removes the elements from the array.
Return Value
<script type="text/javascript">
</script>
concat():
Javascript array concat() method returns a new array comprised of this array joined
with two or more arrays.
Syntax
Return Value
<script type="text/javascript">
var alpha = ["a", "b", "c"];
</script>
slice():
Javascript array slice() method extracts a section of an array and returns a new array.
Syntax
Parameter Details
Return Value
<script type="text/javascript">
</script>
sort():
Syntax
array.sort( compareFunction );
Parameter Details
compareFunction − Specifies a function that defines the sort order. If omitted, the
array is sorted lexicographically.
Return Value
<html>
<head>
</head>
<body>
<script type="text/javascript">
</script>
</body>
</html>
8)Functions:
A function is a group of reusable code which can be called anywhere in your program.
This eliminates the need of writing the same code again and again. It helps programmers
in writing modular codes. Functions allow a programmer to divide a big program into a
number of small and manageable functions.
Function Definition
Before we use a function, we need to define it. The most common way to define a
function in JavaScript is by using the function keyword, followed by a unique function
name, a list of parameters (that might be empty), and a statement block surrounded by
curly braces.
Syntax
The basic syntax is shown here.
<script type="text/javascript">
function functionname(parameter-list)
{
statements
}
</script>
Example
Try the following example. It defines a function called sayHello that takes no
parameters −
<script type="text/javascript">
function sayHello()
{
alert("Hello there");
}
</script>
Calling a Function
To invoke a function somewhere later in the script, you would simply need to write the
name of that function as shown in the following code.
<html>
<head>
<script type="text/javascript">
function sayHello()
{
document.write ("Hello there!");
}
</script>
</head>
<body>
<p>Click the following button to call the function</p>
<form>
<input type="button" value="Say Hello">
</form>
<p>Use different text in write method and then try...</p>
</body>
</html>
Function Parameters
Till now, we have seen functions without parameters. But there is a facility to pass
different parameters while calling a function. These passed parameters can be captured
inside the function and any manipulation can be done over those parameters. A function
can take multiple parameters separated by comma.
Example
Try the following example. We have modified our sayHello function here. Now it takes
two parameters.
<html>
<head>
<script type="text/javascript">
function sayHello(name, age)
{
document.write (name + " is " + age + " years old.");
}
</script>
</head>
<body>
<p>Click the following button to call the function</p>
<form>
<input type="button" 7)" value="Say Hello">
</form>
<p>Use different parameters inside the function and then try...</p>
</body>
</html>
The return Statement
A JavaScript function can have an optional return statement. This is required if you want
to return a value from a function. This statement should be the last statement in a
function.
For example, you can pass two numbers in a function and then you can expect the
function to return their multiplication in your calling program.
Example
Try the following example. It defines a function that takes two parameters and
concatenates them before returning the resultant in the calling program.
<html>
<head>
<script type="text/javascript">
function concatenate(first, last)
{
var full;
full = first + last;
return full;
}
function secondFunction()
{
var result;
result = concatenate('Zara', 'Ali');
document.write (result );
}
</script>
</head>
<body>
<p>Click the following button to call the function</p>
<form>
<input type="button" value="Call Function">
</form>
<p>Use different parameters inside the function and then try...</p>
</body>
</html>
9)Regular Expressions:
A regular expression is an object that describes a pattern of characters.
The JavaScript RegExp class represents regular expressions, and both String
and RegExp define methods that use regular expressions to perform powerful pattern-
matching and search-and-replace functions on text.
Syntax
A regular expression could be defined with the RegExp () constructor, as follows −
pattern − A string that specifies the pattern of the regular expression or another
regular expression.
attributes − An optional string containing any of the "g", "i", and "m" attributes
that specify global, case-insensitive, and multi-line matches, respectively.
Brackets
Brackets ([]) have a special meaning when used in the context of regular expressions. They are used
to find a range of characters.
[...]
Any one character between the brackets.
[^...]
Any one character not between the brackets.
[0-9]
It matches any decimal digit from 0 through 9.
[a-z]
It matches any character from lowercase a through lowercase z.
[A-Z]
It matches any character from uppercase A through uppercase Z.
[a-Z]
It matches any character from lowercase a through uppercase Z.
Quantifiers
The frequency or position of bracketed character sequences and single characters can
be denoted by a special character. Each special character has a specific connotation.
The +, *, ?, and $ flags all follow a character sequence.
p+
It matches any string containing one or more p's.
p*
It matches any string containing zero or more p's.
p?
It matches any string containing at most one p.
p{N}
It matches any string containing a sequence of N p's
p{2,3}
It matches any string containing a sequence of two or three p's.
p{2, }
It matches any string containing a sequence of at least two p's.
p$
It matches any string with p at the end of it.
\s
a whitespace character (space, tab, newline)
\S
non-whitespace character
\d
a digit (0-9)
\D
a non-digit
\w
a word character (a-z, A-Z, 0-9, _)
\W
a non-word character
[\b]
a literal backspace (special case).
[aeiou]
matches a single character in the given set
[^aeiou]
matches a single character outside the given set
(foo|bar|baz)
matches any of the alternatives specified
<head>
<title>Match a Single Character Using Regular Expression in JavaScript</title>
</head>
<body>
<script>
var regex = /ca[kf]e/g;
var str = "He was eating cake in the cafe.";
if(regex.test(str)) {
document.write("Match found!");
} else {
document.write("Match not found.");
}
</script>
</body>
</html>
Ex2
<html>
<head>
<title>JavaScript Find and Replace Characters in a String Using Regular
Expression</title>
</head>
<body>
<script>
var regex = /\s/g;
var replacement = "-";
var str = "Earth revolves around\nthe\tSun";
document.write("<pre>" + str + "</pre>");
document.write("<pre>" + str.replace(regex, replacement) + "</pre>");
document.write("<pre>" + str.replace(/ /g, "-") + "</pre>");
</script>
</body>
</html>
10)JavaScript - Errors & Exceptions Handling:
There are three types of errors in programming: (a) Syntax Errors, (b) Runtime Errors,
and (c) Logical Errors.
Syntax Errors
Syntax errors, also called parsing errors, occur at compile time in traditional
programming languages and at interpret time in JavaScript.
For example, the following line causes a syntax error because it is missing a closing
parenthesis.
<script type="text/javascript">
window.print(;
</script>
When a syntax error occurs in JavaScript, only the code contained within the same thread
as the syntax error is affected and the rest of the code in other threads gets executed
assuming nothing in them depends on the code containing the error.
Runtime Errors
For example, the following line causes a runtime error because here the syntax is correct,
but at runtime, it is trying to call a method that does not exist.
<script type="text/javascript">
window.printme();
</script>
Exceptions also affect the thread in which they occur, allowing other JavaScript threads
to continue normal execution.
Logical Errors
Logic errors can be the most difficult type of errors to track down. These errors are not
the result of a syntax or runtime error. Instead, they occur when we make a mistake in
the logic that drives our script and we do not get the result as we expected.
<script type="text/javascript">
try {
Code to run
[break;]
catch ( e ) {
[break;]
finally {
an exception occurring
</script>
The try block must be followed by either exactly one catch block or one finally block
(or one of both). When an exception occurs in the try block, the exception is placed in
e and the catch block is executed. The optional finally block executes unconditionally
after try/catch.
You can use finally block which will always execute unconditionally after the try/catch.
We can use throw statement to raise your built-in exceptions or your customized
exceptions. Later these exceptions can be captured and you can take an appropriate
action.
<html>
<body>
<script>
function myFunction() {
var message, x;
message = document.getElementById("p01");
message.innerHTML = "";
x = document.getElementById("demo").value;
try {
x = Number(x);
catch(err) {
</script>
</body>
</html>
<script>
</script>
<script>
function emp(id,name,salary){
this.id=id;
this.name=name;
this.salary=salary;
</script>
objectName.property // person.age
or
objectName["property"] // person["age"]
You can add new properties to an existing object by simply giving it a value.
Assume that the person object already exists - you can then give it new properties:
Example
person.nationality = "English";
objectName.methodName()
Example
name = person.fullName();
12)document object:
writeln("string") writes the given string on the doucment with newline character at the
end.
getElementsByName() returns all the elements having the given name value.
<script type="text/javascript">
function printvalue(){
var name=document.form1.name.value;
alert("Welcome: "+name);
}
</script>
<form name="form1">
Enter Name:<input type="text" name="name"/>
<input type="button" value="print name"/>
</form>
<script type="text/javascript">
function getcube(){
var number=document.getElementById("number").value;
alert(number*number*number);
}
</script>
<form>
Enter No:<input type="text" id="number" name="number"/><br/>
<input type="button" value="cube" > </form>
Window Object
The window object represents a window in browser. An object of window is created automatically by
the browser.
confirm() displays the confirm dialog box containing message with ok and cancel button.
setTimeout() performs action after specified time like calling function, evaluating expressions
etc.
<html>
<body>
<p>Click the button to open a new window called "MsgWindow" with some text.</p>
<button >
<script>
function myFunction() {
myWindow= window.open("", "_blank",
"toolbar=yes,scrollbars=yes,resizable=no,top=200,left=300,width=400,height=400");
function closeWin() {
myWindow.close();
</script>
</body>
</html>
EX:<html>
<body>
<script type="text/javascript">
function msg(){
setTimeout(
function(){
alert("Welcome to Javatpoint after 2 seconds")
},2000);
}
</script>
</html>
Navigator Object:
The JavaScript navigator object is used for browser detection. It can be used to
get browser information such as appName, appCodeName, userAgent etc.
<script>
document.writeln("<br/>navigator.appCodeName: "+navigator.appCodName);
document.writeln("<br/>navigator.appName: "+navigator.appName);
document.writeln("<br/>navigator.appVersion: "+navigator.appVersion); </script
>
Date Object:
The JavaScript date object can be used to get year, month and day. You can display a timer on the
webpage by the help of JavaScript date object.
You can use different Date constructors to create date object. It provides methods to get and set day,
month, year, hour, minute and seconds.
Constructor
1. Date()
2. Date(milliseconds)
3. Date(dateString)
4. Date(year, month, day, hours, minutes, seconds, milliseconds)
getDate() It returns the integer value between 1 and 31 that represents the day for
the specified date on the basis of local time.
getDay() It returns the integer value between 0 and 6 that represents the day of the
week on the basis of local time.
getFullYears() It returns the integer value that represents the year on the basis of local
time.
getHours() It returns the integer value between 0 and 23 that represents the hours on
the basis of local time.
getMilliseconds() It returns the integer value between 0 and 999 that represents the
milliseconds on the basis of local time.
getMinutes() It returns the integer value between 0 and 59 that represents the minutes
on the basis of local time.
getMonth() It returns the integer value between 0 and 11 that represents the month on
the basis of local time.
getSeconds() It returns the integer value between 0 and 60 that represents the seconds
on the basis of local time.
setDate() It sets the day value for the specified date on the basis of local time.
setMonth() It sets the month value for the specified date on the basis of local time.
DHTML makes a webpage dynamic but Javascript also does, the question arises that
what different does DHTML do? So the answer is that DHTML has the ability to change a
webpages look, content and style once the document has loaded on our demand without
changing or deleting everything already existing on the browser’s webpage. DHTML can
change the content of a webpage on demand without the browser having to erase
everything else, i.e. being able to alter changes on a webpage even after the document
has completely loaded.
14)Form Validation:
Form validation normally used to occur at the server, after the client had entered all the
necessary data and then pressed the Submit button. If the data entered by a client was
incorrect or was simply missing, the server would have to send all the data back to the
client and request that the form be resubmitted with correct information. This was really
a lengthy process which used to put a lot of burden on the server.
JavaScript provides a way to validate form's data on the client's computer before sending
it to the web server. Form validation generally performs two functions.
● Basic Validation − First of all, the form must be checked to make sure all the
mandatory fields are filled in. It would require just a loop through each field in the
form and check for data.
● Data Format Validation − Secondly, the data that is entered must be checked
for correct form and value. our code must include appropriate logic to test
correctness of data
EX-1
<html>
<body>
<script>
● function validateform(){
var name=document.myform.name.value;
var password=document.myform.password.value;
if (name==null || name==""){
alert("Name can't be blank");
return false;
}
else if(password.length<6){
alert("Password must be at least 6 characters long.");
return false;
}
}
</script>
<script>
function validateemail()
{
var x=document.myform.email.value;
var atposition=x.indexOf("@");
var dotposition=x.lastIndexOf(".");
if (atposition<1 || dotposition<atposition+2 || dotposition+2>=x.length){
alert("Please enter a valid e-
mail address \n atpostion:"+atposition+"\n dotposition:"+dotposition);
return false;
}
}
</script>
<body>
<form name="myform" method="post" action="#" validateema
il();">
Email: <input type="text" name="email"><br/>
<input type="submit" value="register">
</form>
15)Window object:
Open() :
The open() method opens a new browser window.
Syntax
URL Optional. Specifies the URL of the page to open. If no URL is specified, a new
window with about:blank is opened
name Optional. Specifies the target attribute or the name of the window. The
following values are supported:
left=pixels The left position of the window. Negative values not allowed
scrollbars=yes|no|1| Whether or not to display scroll bars. IE, Firefox & Opera only
0
titlebar=yes|no|1|0 Whether or not to display the title bar. Ignored unless the calling
toolbar=yes|no|1|0 Whether or not to display the browser toolbar. IE and Firefox only
top=pixels The top position of the window. Negative values not allowed
Close():
Used to close the current window.
Sy:
window.close();
Ex
<html>
<body>
<p>Click the button to open a new window called "MsgWindow" with some text.</p>
<button >
<script>
function myFunction() {
myWindow= window.open("", "_blank",
"toolbar=yes,scrollbars=yes,resizable=no,top=200,left=300,width=400,height=400");
function closeWin() {
myWindow.close();
</script>
</body>
</html>
An alert box can still be used for friendlier messages. Alert box gives only one button
"OK" to select and proceed.
Example
<html>
<head>
function Warn() {
</script>
</head>
<body>
<form>
<input type = "button" value = "Click Me" />
</form>
</body>
</html>
If the user clicks on the OK button, the window method confirm() will return true. If
the user clicks on the Cancel button, then confirm() returns false.
Example
<html>
<head>
function getConfirmation() {
return true;
} else {
return false;
</script>
</head>
<body>
<form>
</form>
</body>
</html>
Prompt Dialog Box
The prompt dialog box is very useful when you want to pop-up a text box to get user
input. Thus, it enables you to interact with the user. The user needs to fill in the field
and then click OK.
This dialog box is displayed using a method called prompt() which takes two
parameters: (i) a label which you want to display in the text box and (ii) a default string
to display in the text box.
This dialog box has two buttons: OK and Cancel. If the user clicks the OK button, the
window method prompt() will return the entered value from the text box. If the user
clicks the Cancel button, the window method prompt() returns null.
Example
<html>
<head>
function getValue() {
</script>
</head>
<body>
<form>
</form>
</body>
</html>
17)status :
The status property sets the text in the status bar at the bottom of the browser, or
returns the previously set text.
<html>
<head>
<script type="text/javascript">
function statwords(message)
window.status = message;
</script>
</head>
<center>
<form>
</form>
</center> </html>
18)Rollover Buttons:
A rollover button is a dynamic web button that changes appearance depending on the
location of the users mouse pointer. It contains three stages: normal, over and down.
The normal state appears when mouse is off the button , the over state applies when
your mouse rolls over the button, and the down state applies to when you click on the
button.
Rollover buttons come in different shapes , sizes, colors and styles. Rollover buttons
extend the normal functionality of a button.
onmouseenter The event occurs when the pointer is moved onto an element
onmousemove The event occurs when the pointer is moving while it is over an element
onmouseout The event occurs when a user moves the mouse pointer out of an
element, or out of one of its children
onmouseover The event occurs when the pointer is moved onto an element, or onto
one of its children
EX:
<html>
<head>
<style>
div {
width: 100px;
height: 100px;
border: 1px solid black;
margin: 10px;
padding: 30px;
text-align: center;
background-color: lightseagreen;
}
p{
background-color: cyan;
}
</style>
<script>
function mouseover()
{
document.myimg.src="a.jpg";
}
function mouseout()
{
document.myimg.src="b.jpg";
}
var x = 0;
var y = 0;
var z = 0;
function myMoveFunction() {
document.getElementById("demo").innerHTML = z+=1;
}
function myEnterFunction() {
document.getElementById("demo2").innerHTML = x+=1;
}
function myOverFunction() {
document.getElementById("demo3").innerHTML = y+=1;
}
</script>
<body>
<img src="b.jpg" name="myimg" width="200px" height="250px"
><div > <p>onmousemove: <br> <span id="demo">Mouseover me!</span></p>
</div>
<div > <p>onmouseenter:<br> <spanid="demo2">Mouseover me!</span></p>
</div>
<div > <p>onmouseover:<br> <span id="demo3">Mouse over me!</span></p>
</div>
</body>
</html>
19)MOVING IMAGE:
JavaScript can be used to move an image around the web page according to some sort
of pattern determined by a logical equation or function. In fact this is not a moving image
at all, that’s just the effect. What is actually moving is a layer of content.
To make an animation possible, the animated element must be animated relative to a
“parent container”. The container element should be created with
style=”position:relative|absolute”.
JavaScript provides the following function for this animation
setTimeout(function,duration)
The function calls function after duration milliseconds from now.
<HTML>
<script type="text/javascript">
var x=0;
function move()
{
document.a.style.marginLeft=x+"%";
x=x+10;
if(x==100)
x=0;
var t=setTimeout("move()",500);
}
</script>
<BODY >
</BODY>
</HTML>
Ex-2
<html>
<script type="text/javascript">
function moveleft()
{
document.getElementById('image').style.position="absolute";
document.getElementById('image').style.left="0";
}
function moveback()
{
document.getElementById('image').style.position="absolute";
}
</script>
<body>
<img id="image" src="./face.gif"
> />
</body>
</html>
When a frameset is loaded into the main window a frame tree is created. The
window, which JavaScript calls top, holds some frames underneath it. If these frames
have nested framesets inside themselves, then a further level is added to the tree. A
page with frames set up as on the left will have a frame tree as on the right: