SlideShare a Scribd company logo
1 of 372
JAVA SCRIPT
1
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.
2
JavaScript has been around for several years now, in many
different flavors. The main benefit of Javascript is to add
additional interaction between the web site and its visitors
at the cost of a little extra work by the web developer.
Javascript allows industrious web masters to get more out
of their website than HTML and CSS can provide.
3
By definition, Javascript is a client-side scripting language.
This means the web surfer's browser will be running the
script. This is opposite to client-side is server-side, which
occurs in a language like PHP. These PHP scripts are run by
the web hosting server.
There are many uses (and abuses!) for the powerful
Javascript language. Here are a few things that you may or
may not have seen in your web surfing days.
4
Example of java scripts:
Clocks
Mouse Trailers (an animation that follows your mouse
when you surf a site)
Drop Down Menus
Alert Messages
Popup Windows
Html form Data Validation
5
Advantages of JavaScript
Less server interaction − You can validate user input before sending
the page off to the server. This saves server traffic, which means less
load on your server.
Immediate feedback to the visitors − They don't have to wait for a
page reload to see if they have forgotten to enter something.
Increased interactivity − You can create interfaces that react when
the user hovers over them with a mouse or activates them via the
keyboard.
Richer interfaces − You can use JavaScript to include such items as
drag-and-drop components and sliders to give a Rich Interface to your
site visitors.
Limitations of JavaScript
We cannot treat JavaScript as a full-fledged
programming language. It lacks the following important
features −
• 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 multi-threading or
multiprocessor capabilities.
Syntax of Java Script
JavaScript can be implemented using JavaScript statements that are placed
within the <script>... </script> HTML tags in a web page.
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>
The script tag takes two important attributes −
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".
So your JavaScript segment will look like −
<script language = "javascript" type = "text/javascript">
JavaScript code
</script>
Whitespace and Line Breaks
JavaScript ignores spaces, tabs, and newlines that appear in JavaScript
programs.
Semicolons are Optional
Simple statements in JavaScript are generally followed by a semicolon character,
just as they are in C, C++, and Java. JavaScript, however, allows you to omit this
semicolon if each of your statements are placed on a separate line. For example,
the following code could be written without semicolons.
<script language = "javascript" type = "text/javascript">
<!--
var1 = 10
var2 = 20
//-->
</script>
But when formatted in a single line as follows, you must use semicolons −
<script language = "javascript" type = "text/javascript">
<!--
var1 = 10; var2 = 20;
//-->
</script>
Case Sensitivity
JavaScript is a case-sensitive language. This means that the language keywords,
variables, function names, and any other identifiers must always be typed with a
consistent capitalization of letters.
So the identifiers Time and TIME will convey different meanings in JavaScript.
Comments in JavaScript
JavaScript supports both C-style and C++-style comments, Thus −
• Any text between a // and the end of a line is treated as a comment and is ignored
by JavaScript.
• Any text between the characters /* and */ is treated as a comment. This may span
multiple lines.
• JavaScript also recognizes the HTML comment opening sequence <!--. JavaScript
treats this as a single-line comment, just as it does the // comment.
• The HTML comment closing sequence --> is not recognized by JavaScript so it
should be written as //-->.
Example
The following example shows how to use comments in JavaScript.
<script language = "javascript" type = "text/javascript">
<!--
// This is a comment. It is similar to comments in C++
/*
* This is a multi-line comment in JavaScript
* It is very similar to comments in C Programming
*/
//-->
</script>
How To Write Javascript
If you have ever used CSS before, then the whole
part about how to include Javascript will be a lot
simpler to grasp. Here are three important steps you
should always take when creating or using someone
else's Javascript code.
12
Use the script tag to tell the browser you are using
Javascript.
Write or download some Javascript
Test the script!
There are so many different things that can go
wrong with a script, be it human error, browser
compatability issues, or operating system
differences. So whenever using Javascript, be sure
that you test your script out on a wide variety of
systems and most importantly, different web
browsers.
13
Your First Javascript Script
To follow the classic examples of many programming
let's use Javascript to print out "Hello World" to the
browser. I know this isn't very interesting, but it will
be a good way to explain all the overhead required
to do something in Javascript
14
HTML & JavaScript Code:
<html>
<body>
<script type="text/javascript">
document.write("Hello World!")
</script>
</body>
</html>
15
Our first step was to tell the browser we were using a
script with <script> tag. Next we set the type of script
equal to "text/javascript", which you may notice that
doing this is similar to the way you specify CSS, which
is "text/css".
Next we added an optional HTML comment that
surrounds our Javascript code. If a browser does not
support Javascript, then it will not display our code in
plain text to the user! The comment was ended with a
"//-->" because "//" signifies a comment in Javascript,
so we add that to prevent a browser from reading the
end of the HTML comment in as a piece of Javascript
code.
16
Javascript document.write
The final step of our script was to use a function called
document.write which writes a string into our HTML
document. document.write can be used to write text,
HTML, or a little of both. We passed the famous string of
text to the function to spell out "Hello World!" which it
printed to the screen.
17
Syntax
Looking at our Javascript code above, notice that there is
no semicolon at the end of the statement
"document.write(Hello World!)". Why? Because Javascript
does not require that you use semicolons to signify the end
of each statement.
If you are an experienced programmer and prefer to use
semicolons, feel free to do so. Javascript will not
malfunction from ending semicolons. The only time it is
necessary to use a semicolon is when you choose to smash
two statements onto one line(i.e. two document.write
statements on one line).
18
Javascript - Is it Enabled?
This lesson will first teach you how to enable
Javascript in Internet Explorer then show you how
you can write a very simple script to separate those
who don't have Javascript enabled from those that
do on your websites.
19
Enable Javascript - Internet Explorer
In Internet Explorer 6/7 (download Internet Explorer) you
can check to see if Javascript is enabled by navigating to
the custom security settings that are somewhat buried
(don't worry we'll help you find it).
Click on the Tools menu
Choose the Internet Options... from the menu
Click the Security tab on the Internet Options pop up
Click the Custom Level... button to access your security
settings
Scroll almost all the way down to the Scripting section
Select the Enable button for Active scripting
Click OK to finish the process
Click Yes when asked to confirm
20
Javascript Detection
These days it's basically impossible to navigate the
web without a Javascript enabled browser, so
checking whether or not a user has Javascript
enabled is not all that important. Chances are the
only way it be disabled is if the company's IT staff
has decided to disable Javascript for some reason.
However, if you still want to be sure your users are
Javascript enabled, this script will get it done
21
The only sure fire way to separate users that
don't have Javascript from those that do is to
use a simple redirect script that will only work
for those with Javascript enabled. If a person's
browser does not have Javascript enabled the
script will not run and they will remain on the
same page.
22
Javascript Code:
<script type="text/javascript">
window.location =“tt.html"
</script>
23
Where to Place Javascript
There are three general areas that
Javascript can be placed for use in a web
page.
24
Inside the head tag
Within the body tag
In an external file
The location choice of head or body is very simple. If you
want to have a script run on some event, such as when a
user clicks somewhere, then you will place that script in
the head. If you want the script to run when the page
loads, like our "Hello World!" example , then you will want
to place the script within the body tag.
25
An Example Head Script
Since we have already seen the kind of script that
goes in the body, how about we write a script that
takes place when some event occurs, say a click on a
button.
26
HTML & JavaScript Code:
<html>
<head>
<script type="text/javascript">
function popup()
{
document.write("Hello World!")
}
</script> </head>
<body>
<input type="button" onclick="popup()" value="popup">
</body>
</html>
27
28
29
We created a function called popup and placed it in
the head of the HTML document. Now every time
someone clicks on the button (this is an event)
"Hello World!“ will be display. We will go into more
depth on functions and events in a later .
30
External Javascript Files
Having already dicussed placing Javascript in
the head and body of your HTML document,
let us now explore the third possible
location, an external file.
31
Importing an External Javascript File
Importing an external file is relatively painless. First the
file you are importing must be valid Javascript, and only
Javascript. Second, the file must have the extension ".js".
Lastly, you must know the location of the file.
Let us assume we have a file "myjs.js" that contains a one
line Hello World alert function. Also, let us assume that the
file is the same directory as our HTML file we are going to
code up. To import the file you would do the following in
your HTML document.
32
HTML & JavaScript Code:
<html>
<head>
<script src="myjs.js">
</script>
</head>
<body> <input type="button" onclick="popup()"
value="Click Me!">
</body>
</html>
33
function popup()
{
document.write("Hello World!")
}
myjs.js
34
35
36
37
Great Javascript Repositories
There is a ton of great stuff you can do with
Javascript, if you know how to code like Paul Allen
and Bill Gates, but for the rest of us it is nice to get
incredible Javascript tools without having to write
them ourselves. Below are some of the better
Javascript resources on the web these days.
JavaFile.com
Java-Scripts.com
38
External File Tips & Recap
Use external Javascript files when you want to use the same
script on many pages, but don't want to have to rewrite the
code on every page!
Use external Javascript files for including both types of
scripts! The type that you place in the head (functions) and
the type you place in the body (scripts you want to run
when the page loads).
Be sure that your Javascript files (.js) do not include the
<script> tag. They should only have the HTML comment and
Javascript code.
39
Javascript Operators
Operators in Javascript are very similar to
operators that appear in other programming
languages. The definition of an operator is a
symbol that is used to perform an operation.
Most often these operations are arithmetic
(addition, subtraction, etc), but not always.
40
Javascript Arithmetic Operator Chart
41
Operator English Example
+ Addition 2 + 4
- Subtraction 6 - 2
* Multiplication 5 * 3
/ Division 15 / 3
% Modulus 43 % 10
42
Assignment operator
Operator Example Same As
= x = y x = y
+= x += y x = x + y
-= x -= y x = x - y
*= x *= y x = x * y
/= x /= y x = x / y
%= x %= y x = x % y
**= x **= y x = x ** y
Javascript Operator Example with Variables
Performing operations on variables that
contain values is very common and easy to
do. Below is a simple script that performs all
the basic arithmetic operations
44
<html>
<body>
<script type="text/javascript">
var two=2
var ten=10
document.write("two + ten = ")
result=two + ten
document.write(result)
</script>
</body>
<html>
45
46
<html>
<body>
<script type="text/javascript">
var two=2
var ten=10
document.write("two - ten = ")
result=two - ten
document.write(result)
</script>
</body>
<html>
47
48
Comparison Operators
Comparisons are used to check the relationship
between variables and/or values. A single equal sign
sets a value while a double equal sign (==) compares
two values. Comparison operators are used inside
conditional statements and evaluate to either true
or false.
49
Operator English Example Result
== Equal To x == y false
!= Not Equal To x != y true
< Less Than x < y true
> Greater Than x > y false
<= Less Than or Equal To x <= y true
>= Greater Than or Equal To x >= y false
50
Logical operator
Operator Description
&& logical and
|| logical or
! logical not
String Operator:The + operator can also be u
to add (concatenate) strings.
Type operator
Operator Description
typeof Returns the type of a variable
instanceof Returns true if an object is an
instance of an object type
Bitwise operator
Operator Descriptio
n
Example Same as Result Decimal
& AND 5 & 1 0101 &
0001
0001 1
| OR 5 | 1 0101 |
0001
0101 5
~ NOT ~ 5 ~0101 1010 10
^ XOR 5 ^ 1 0101 ^
0001
0100 4
<< Zero fill
left shift
5 << 1 0101 << 1 1010 10
>> Signed
right shift
5 >> 1 0101 >> 1 0010 2
>>> Zero fill
right shift
5 >>> 1 0101 >>> 1 0010 2
JavaScript Variables
Variables in Javascript behave the same as
variables in most popular programming
languages (C, C++, etc) except that you don't
have to declare variables before you use
them. If you don't know what declaring is,
don't worry about it, it isn't important!
54
Javascript Using Variables
A variable's purpose is to store information so that it
can be used later. A variable is a symbolic name that
represents some data that you set. To think of a
variable name in real world terms, picture that the
name is a grocery bag and the data it represents are
the groceries. The name wraps up the data so you
can move it around a lot easier, but the name is not
the data!
55
A Variable Example
When using a variable for the first time it is
not necessary to use "var" before the variable
name, but it is a good programming practice
to make it crystal clear when a variable is
being used for the first time in the program.
Here we are showing how the same variable
can take on different values throughout a
script
56
<body>
<script type="text/javascript">
var linebreak = "<br />“
var my_var = "Hello World!“;
document.write(my_var)
document.write(linebreak)
my_var = "I am learning javascript!"
document.write(my_var);
document.write(linebreak)
my_var = "Script is Finishing up..."
document.write(my_var)
</script> </body>
57
58
We made two variables in this example. One to hold the
HTML for a line break and the other was a dynamic variable
that had a total of three different values throughout the
script.
To assign a value to a variable you use the equal sign (=)
with the variable on the left and the value to be assigned
on the right. If you swap the order then your script will not
work correctly! In english the Javascript "myVar = 'Hello
World!'" would be: myVar equals 'Hello World!'.
The first time we used a variable we placed var in front to
signify its first use. In subsequent assignments of the same
variable we did not need the var.
59
Javascript Variable Naming Conventions
When choosing a variable name you must first be
sure that you do not use any of the Javascript
reserved names . Another good practice is choosing
variable names that are descriptive of what the
variable holds. If you have a variable that holds the
size of a shoe, then name it "shoe_size" to make
your Javascript more readable.
60
Finally, Javascript variable names may not start with
a numeral (0-9). These variable names would be
illegal: 7lucky, 99bottlesofbeer, and 3zacharm.
A good rule of thumb is to have your variable names
start with a lowercase letter (a-z) and use
underscores to separate a name with multiple words
(i.e. my_var, strong_man, happy_coder, etc).
61
Javascript Functions
If you have any programming experience, then you
do not need to spend much time on this . Functions
in Javascript behave similar to numerous
programming languages (C, C++, PHP, etc). If this is
your first time learning about functions, then be
sure to go through this very thoroughly as a solid
understanding of functions will make the rest of this
easier to follow
62
What's a Function?
A function is a piece of code that sits dormant until
it is referenced or called upon to do its "function". In
addition to controllable execution, functions are
also a great time saver for doing repeatable tasks.
Instead of having to type out the code every time
you want something done, you can simply call the
function multiple times to get the same effect. This
benefit is also known as "code reusability”
63
Example Function in Javascript
A function does not execute when the page
loads and so it should be placed inside the
head of your HTML document. Creating a
function is really quite easy, all you have to
do is tell the browser you're making a
function, give the function a name, and then
write the Javascript like normal.
64
HTML & JavaScript Code:
<html>
<head>
<script type="text/javascript">
function popup()
{
document.write("Hello World!")
}
</script> </head>
<body>
<input type="button" onclick="popup()" value="popup">
</body>
</html>
65
We first told the browser we were going to be using
a function by typing "function". Next, we gave our
function a name, so that we could use it later. Since
we are making a pop up , we called our function
"popup".
The curly braces "{,}" define the boundaries of our
function code. All popup function code must be
contained within the curly braces.
66
What we didn't talk about was how we got
this function to execute when the button is
clicked. The click is called an event, and we
will be talking about how to make functions
execute from various types of events in the
next lesson.
67
Writing Your Own Function
You can also make your own functions to
be used on your webpage. If you would
like to write your own function then you
must use the special keyword function
68
Events in Javascript
The absolute coolest thing about Javascript is the
ability to create dynamic web pages that increase
user interaction, making the visitor feel like the
website is almost coming alive right before their
eyes.
69
The building blocks of an interactive web page is the
Javascript event system. An event in Javascript is
something that happens with or on the web page. A
few example of events:
A mouse click
The web page loading
Mousing over a hot spot on the web page, also
known as hovering
Selecting an input box in an HTML form
A keystroke
70
A Couple of Examples Using Events
Javascript has predefined names that cover
numerous events that can occur, including the ones
listed above. To capture an event and make
something happen when that event occurs you must
specify the event, the HTML element that will be
waiting for the event, and the function(s) that will
be run when the event occurs.
71
<html>
<head>
<script type="text/javascript">
function popup()
{
document.write("hello")
} </script>
</head>
<body>
<input type="button" value="Click Me!" onclick="popup()">
<br />
<a href="#" onmouseover="popup()" > Hover Me!</a>
</body>
</html>
72
73
74
<html>
<head>
<script type="text/javascript">
function popup()
{
document.write("hello")
} </script>
</head>
<body>
<input type="button" value="Click Me!" onclick="popup()">
<br />
<a href="#" onmouseout="popup()" > Hover Me!</a>
</body>
</html>
75
76
77
With the button we used the event onClick event as
our desired action and told it to call our popup
function that is defined in our header. To call a
function you must give the function name followed
up with parenthesis "()".
Our mouseover and mouseout events were combined
on one HTML element, a link. We wanted to do
nothing when someone put their mouse on the link,
but when the mouse leaves (onMouseout) we
displayed a popup.
78
<html>
<head>
<script type="text/javascript">
function popup()
{
document.write("hello")
}
</script>
</head>
<body>
<input type="button" value="Click Me!"
onmouseout="popup()">
<br />
</body>
</html>
79
80
81
82
Javascript Statements
All the Javascript code that you will write
will, for the most part, be comprised of many
separate statements. A statement is setting a
variable equal to a value. A statement is also
a function call, i.e. document.write().
Statements define what the script will do
and how it will be done.
83
Typical Ending of a Statement
In typical programming languages like C , the
end of a statement is marked with a
semicolon(;), but we have seen that the
colon is optional in javascript. In Javascript
the end of a statement is most often marked
by starting a new line.
84
Categories of Statements
In addition to the standard statements like changing
a variable's value, assigning a new value, or calling a
function, there are groups of statements that are
distinct in their purpose. We will provide a brief
overview of each of these categories .
Conditional Statements
Loop Statements
Object Manipulation Statements
Comment Statements
Exception Handling Statements
85
Conditional Statements
If you were to win a 100 la Rs lottery then you would
probably quit your job. That last statement is a
conditional if/then statement that is used a great
deal in programming. If some condition (winning the
lottery) is true, then something happens (you quit
your job). If the condition is false, then you probably
will not take that action (quit your job).
86
Conditional statements are used to control your
scripts so that different actions can be taken
depending on the situation. You may want to display
a special image on your home page during the
holidays. This condition would depend on what day it
was, and if it was a holiday, then a special holiday
image would be displayed to your visitors. Without
proper knowledge of the conditional statement your
scripts will not be as lively or dynamic as they could
possibly be.
87
Loop Statements
Have you ever had to send out marriage
announcements? If not, this is how it goes. You take
the invitation, place it in the envelope, lick the
envelope, seal the envelope, then send it off. Then
you take the next invitation off the stack of 99
remaining invitations, place it in an envelope, lick
the envelope, seal... You get the idea! It is a boring,
repetitive task!
Wouldn't it be great if there was an easier way? Well
in programming and in Javascript there is. The
process is called "looping" and it will turn your cute
little scripts into massive work horses with the right
planning
88
A loop statement checks to see if some condition is
true, say our condition is "Are there any invitations
left?" and if that condition is true it will execute a
chunk of code. Our code in this example would be to
stuff, lick, and seal the envelope. After the code is
executed the condition is checked again, if it is true
then the process begins again, if it is false, then the
loop code stops execution and the script continues
along.
Believe me when I say this is something you want to
learn more about!
89
Object Manipulation Statements
These are statements that are used to take
advantage of the object model to get tasks
done. If you do not know about the object
model at this time, do not worry. We will be
talking about it later.
90
Comment Statements
Comment statements are used to prevent the
browser from executing certain parts of code that
you designate as non-code. Why would you want to
do this? There are many reasons. By disallowing the
block of text to be read you can then place in
comments for yourself, much like HTML comments,
and you can also block out segments of your code for
whatever reason you may have.
The single line comment is just two slashes (//) and
the multiple line comment starts with (/*) and ends
with (*/).
91
Exception Handling Statements
Sometimes when you are programming you do not know for
sure if the file that you will be writing to, the input stream
you are reading from, or the connection you have
established will be usable for the code that you want to
execute. There is a way to program safety mechanisms, so
that your code handles common problems that may arise
(maybe the input stream you are reading from suddenly
disappears).
The try...catch statement tries to execute a piece of code
and if it fails the catch should handle the error gracefully.
This is an advanced programming subject that is interesting,
but not necessary for the majority of Javascript
programmers.
92
Javascript If Statement
As your Javascript programs get more
sophisticated you will need to make use of
conditional statements that allow your
program to make decisions. Nearly all other
programming languages use conditionals and
Javascript is no exception.
93
The If Statement is a way to make decisions
based on a variable or some other type of
data. For example you might have a variable
that stores the date. With this tiny bit of
information you could easily program a small
script to print out "Today is my Birthday!"
whenever the day and month were equal to
your birthday
94
Javascript If Statement Syntax
There are two major parts to an if statement: the
conditional statement and the code to be executed.
The conditional statement is a statement that will
evaluate to either True or False. The most common
type of a conditional statement used is checking to
see if something equals a value. An example would
be checking if the date equaled your birthday.
95
The code to be executed contains the
Javascript code that will be executed only if
the If Statement's conditional statement was
true. In this simple If Statement example we
print out a message if the variable we are
checking is equal to 7.
96
<html>
<body>
<script type="text/javascript">
var myNum = 7
if(myNum == 7)
{
document.write("Lucky 7!")
}
</script>
</body>html>
97
98
This simple example created myNum and set it to 7.
We then checked to see if myNum was equal to 7
"myNum == 7" in the If Statement's conditional
statement which evaluated to True.
Because the conditional statement was True the
block of code associated with our If Statement
"document.write..." was executed, as you can see in
the Display.
99
Javascript If Statement: Else
We already taught you how to execute code if a
given condition is True, but what if you want to
execute another piece of code if something is False?
The answer is to use an extension to the If
Statement; the Else clause.
The Else clause is executed when the conditional
statement is False. Let's take our example from
above, add an Else clause and change the value of
myNum so that our conditional statement is False.
100
<html>
<script type="text/javascript">
var myNum = 10;
if(myNum == 7){ document.write("Lucky
7!"); }
else{
document.write("You're not very lucky
today...");
} </script>
</html>
101
102
<html>
<script type="text/javascript">
var visitor = "principal“
if(visitor == "teacher")
{ document.write("My dog ate my homework..."); }
else
if(visitor == "principal"){ document.write(“hello
principal"); } else { document.write("How do you
do?"); }
</script></html>
103
104
There are two important things to note about
the Else If extension:
You must have a normal If Statement before
you can use the Else If statement. This is
because the Else If statement is an addon to
the If Statement.
You can have multiple Else If add-ons. In our
example we only used one Else If extension,
but you can add as many as you require.
105
Javascript While Loop
The while loop is an advanced programming
technique that allows you to do something
over and over while a conditional statement
is true. Although the general uses of the
while loop are usually a bit complex, this
lesson will teach you the basics of how to
create a while loop in Javascript
106
Javascript While Loop Explained
There are two key parts to a Javascript while loop:
The conditional statement which must be True for the while
loop's code to be executed.
The while loop's code that is contained in curly braces "{
and }" will be executed if the condition is True.
When a while loop begins the Javascript interpreter checks
the condition statement is true. If it is the code between
the curly braces is executed. At the end of the code
segment "}" the while loop loops back to the condition
statement and begins again.
If the condition statement is always True then you will
never exit the while loop, so be very careful when using
while loops
107
Creating a Simple While Loop
This example shows how to create a
basic while loop that will execute a
document.write 10 times and then exit
the loop statement.
108
<html>
<script type="text/javascript">
var myCounter = 0;
var linebreak = "<br />";
document.write("While loop is beginning");
document.write(linebreak);
while(myCounter < 10){
document.write("myCounter = " + myCounter);
document.write(linebreak);
myCounter++;
} document.write("While loop is finished!");
</script> </html>
109
While loop is beginning
myCounter = 0
myCounter = 1
myCounter = 2
myCounter = 3
myCounter = 4
myCounter = 5
myCounter = 6
myCounter = 7
myCounter = 8
myCounter = 9
While loop is finished!
110
Our variable myCounter started off at 0, which is less than
10, so our while loop executed its code. The value 0 was
printed to the browser and then myCounter was
incremented by 1 and the while loop started over again.
1 was less than 10 so the while loop's code was
executed...and the process repeats itself a few more times
until...
myCounter was 10 which was not less than 10 so the while
loop's code did not execute. You can see this in the Display:
because the last value to be printed out was 9.
Note: Advanced programmers may recognize that a for loop
would be a better solution for this example, but we hope
you can ignore this for our needs to create an easy
example!
111
Javascript For Loop Explained
There are four important aspects of a Javascript for loop:
The counter variable is something that is created and
usually used only in the for loop to count how many times
the for loop has looped.
The conditional statement that decides whether the for
loop continues executing or not. This check usually includes
the counter variable in some way.
The counter variable is incremented after every loop in the
increment section of the for loop.
The code that is executed for each loop through the for
loop.
This may seem strange, but 1-3 all occur on the same line
of code. This is because the for loop is such a standardized
programming practice that the designers felt they might as
well save some space and clutter when creating the for
loop. 112
<html>
<script type="text/javascript">
var linebreak = "<br />“
document.write("For loop code is beginning")
document.write(linebreak)
for(i = 0; i < 5; i++)
{ document.write("Counter i = " + i)
document.write(linebreak)
}
document.write("For loop code is finished!");
</script></html>
113
For loop code is beginning
Counter i = 0
Counter i = 1
Counter i = 2
Counter i = 3
Counter i = 4
For loop code is finished!
114
The counter variable name i may seem a little strange, but it has
been used for years now that you might as well get used to it as
the default for loop counter. Other common variable names are j,
k, x and y
So in this example our counter was initially set to 0 with "i = 0;"
and then the conditional statement "i < 5;" was executed. Our
counter was indeed smaller than 5 and so the for loop's code was
executed.
After the loop's code had been executed then the increment "i++"
happens, making the counter i equal to 1. The for loop then
checked that i was less than 5, which it was, resulting in the
loop's code being executed again.
This looping happened a couple more times until i was equal to 5,
which is not less than 5 and the for loop stopped executing.
For loops may seem very confusing at first, but let me assure you,
they are quite useful and should be studied thoroughly by anyone
who wishes to become a intermediate programmer.
115
Javascript Comments
Have you ever written a script or a program in the
past only to look at it 6 months later and have no
idea what's going on in the code? You probably forgot
to do what all programmers tend to forget: write
comments!
116
When writing code you may have some complex logic
that is confusing, this is a perfect opportunity to
include some comments in the code that will explain
what is going on. Not only will this help you
remember it later on, but if you someone else views
your code they will also be able to understand the
code (hopefully)!
Another great thing about comments is the ability
for comments to remove bits of code from execution
when you are debugging your scripts. This lesson will
teach you how to create two types of comments in
Javascript: single line comments and multi-line
comments.
117
Creating Single Line Comments
To create a single line comment in Javascript you
place two slashes "//" in front of the code or text
you wish to have the Javascript interpreter ignore.
When you place these two slashes, all text to the
right will be ignored, until the next line.
These types of comments are create for commenting
out single lines of code and writing small notes.
118
<html>
<script type="text/javascript">
// This is a single line Javascript comment
document.write("I have comments in my
Javascript code!")
//document.write("You can't see this!");
</script>
<html>
119
I have comments in my Javascript code!
120
Creating Multi-line Comments
Although a single line comment is quite
useful, it can sometimes be burdensome to
use for large segments of code you wish to
disable or extra long winded comments you
need to insert. For this large comments you
can use Javascript's multi-line comment that
begins with /* and ends with */.
121
<html>
<script type="text/javascript">
document.write("I have multi-line
comments!"); /*document.write("You can't see
this!"); document.write("You can't see this!");
document.write("You can't see this!");
document.write("You can't see this!");
document.write("You can't see this!");
document.write("You can't see this!");
document.write("You can't see this!");*/
</script>
</html>
122
I have multi-line comments!
Quite often text editors have the ability to
comment out many lines of code with a
simple key stroke or option in the menu. If
you are using a specialized text editor for
programming be sure that you check and see
if it has an option to easily comment out
many lines of code!
123
Javascript Array
An array is a variable that can store
many variables. Many programmers have
seen arrays in other languages and they
aren't that different in Javascript
124
The following points should always be remembered when
using arrays in Javascript:
The array is a special type of variable.
Values are stored into an array by using the array name and
by stating the location in the array you wish to store the
value in brackets.
Example:
myArray[2] = "Hello World";
Values in an array are accessed with the array name and
location of the value.
Example:
myArray[2];
Javascript has built in functions for arrays, so check out
these built in array functions before writing code yourself!
125
Creating a Javascript Array
Creating an array is slightly different than creating a
normal variable. Because Javascript has variables
and properties associated with arrays, you have to
use a special function to create a new array. This
example shows how you would create a simple array,
store values to it and access these values.
126
<html>
<script type="text/javascript">
var myArray = new Array()
myArray[0] = "Baseball”
myArray[1] = "Cricket"
myArray[2] = "Football"
document.write(myArray[0] + myArray[1] +
myArray[2]);
</script></html> 127
128
Display:
FootballBaseballCricket
Notice that you set values and get values
from an array by specifying the position,
in brackets, of the value you want to
use.
129
Javascript Array Sorting
Imagine that you wanted to sort an array
alphabetically before you wrote the
array to the browser. Well, this code has
already been written and can be
accessed by using the Array'ssort
method.
130
<html>
<script type="text/javascript">
var myArray = new Array()
myArray[0] = “q“
myArray[1] = “w“
myArray[2] = “e“
myArray.sort()
document.write(myArray[0] + myArray[1] +
myArray[2]);
</script><html>
131
132
Javascript Alert - What is it?
If you do not have Javascript enabled on your
web browser, then you may have been able
to avoid them in your internet history. The
Javascript alert is a dialogue box that pops
up and takes the focus away from the current
window and forces the web browser to read
the message
133
You may have noticed that you didn't get a
Javascript alert popup when you came to this
page. That is because doing so would be in
bad taste for a web designer. You see, alerts
should be very, very rarely used and even
then these following guidelines should be
considered when using them.
134
When to Use Popups / Alerts
Javascript alerts are ideal for the following situations:
If you want to be absolutely sure they see a message before doing
anything on the website.
You would like to warn the user about something. For example "the
following page contains humor not suitable for those under the age of 14."
An error has occurred and you want to inform the user of the problem.
When asking the user for confirmation of some action. For example they
have just agreed to sign over the deed to their house and you want to ask
them again if they are absolutely positive they want to go through with this
decision!
Even though the above situations would all be valid times to use the alert
function, you could also skip the alert and just have the error message,
confirmation, etc displayed in plain HTML, instead of in a popup. More and
more bigger sites are opting to lose the Javascript alerts and instead keep
everything in HTML.
135
Coding a Simple Javascript Alert
Just for fun, let us suppose that we are
making an alert for some website that asks
people to hand over the deed to their house.
We need to add an alert to be sure these
people are in agreement. The following code
will add an alert by using an HTML button
and the onClick event.
136
<html>
<form>
<input type="button" onclick= "alert('Are you
sure you want to give us the deed to your
house?')" value="Confirmation Alert">
</form>
</html>
137
138
139
Javascript Confirm
The Javascript confirm function is very similar to the
Javascript alert function. A small dialogue box pops
up and appears in front of the web page currently in
focus. The confirm box is different than the alert
box in that it supplies the user with a choice, they
can either press OK to confirm the popups message
or they can press cancel and not agree to the popups
request.
140
Confirmation are most often used to confirm
an important action that is taking place on a
website. For example they may be about to
submit an order or about to visit a link that
will take them away from the current
website.
141
Javascript Confirm Example
142
<html> <head>
<script type="text/javascript">
function confirmation()
{
var answer = confirm(“hello atul")
if (answer)
{
alert("Bye bye!")
window.location = “tt.html“
}
else
{ alert("Thanks for sticking around!") } }
</script> </head>
<body> <form>
<input type="button" onclick="confirmation()" value="Leave atul.com">
</form> </body> </html>
143
144
145
146
147
148
149
Confirm returns the value 1 if the user clicks OK and the
value 0 if the user clicks Cancel. We store this value in
answer by setting it equal to the confirm function call.
After answer has stored the value, we then use answer as a
conditional statement. If answer is anything but zero, then
we are going to send the user away from tt.html . If answer
is equal to zero, then we will keep the user at ttt.html
because they clicked the Cancel button.
In either case we have a Javascript alert box that appears
to inform the user what is going to happen. "Bye bye!" if
they chose to leave and "Thanks for sticking around!" if they
chose to stay
150
In this lesson we also used the
window.location property for the first
time. Whatever we set window.location
to will be where the browser is
redirected to.We will also discuss
redirection later on.
151
Javascript Prompt
The Javascript prompt is a relic from the
1990's that you seldom see being used in
modern day websites. The point of the
Javascript prompt is to gather
information from the user so that it can
be used throughout the site to
"personalize" it for the visitor. 152
Back in the day you'd often see these prompts on
personal web pages asking for your name. After you
typed in the information you would be greeted with
a page that had a welcome message, such as
"Welcome to My Personal Web Page ATUL Kahate!" (If
you name just happened to be ATUL Kahate).
The Javascript prompt is not very useful and many
find it slightly annoying, but hey, this lesson is here
to educate you, so let's learn how to make that
prompt! 153
Simple Javascript Prompt
You can use a prompt for a wide variety of useless
tasks, but below we use it for an exceptionally silly
task. Our prompt is used to gather the user's name
to be displayed in our alert dialogue box.
154
<html>
<head>
<script type="text/javascript">
function prompter() {
var reply = prompt("Hey there, good looking
stranger! What's your name?", "")
alert (reply) } </script> </head>
<body>
<input type="button" onclick="prompter()" value="Say
my name!"> </body>
155
156
157
158
Recap on Javascript Prompt
It sure is a quick way to gather some information, but it is
not as a reliable information gatherer as the other options
available to you. If you want to find out someone's name
and information, the best way to request this information
would be to use HTML Forms.
159
Javascript Print Function
The Javascript print function performs the
same operation as the print option that you
see at the top of your browser window or in
your browser's "File" menu. The Javascript
print function will send the contents of the
webpage to the user's printer.
160
Many believe this function to be worthless,
but there are many computer users that do
not know their way around a computer all
that well and it can sometimes create a more
user friendly experience when you provide as
many helpful features as possible
161
Javascript Print Script - window.print()
The Javascript print function window.print()
will print the current web page when
executed. In this example script we will be
placing the function on a Javascript button
that will perform the print operation when
the onClick event occurs.
162
HTML & Javascript Code:
<HTML>
<form> <input type="button" value="Print This
Page" onClick="window.print()" /> </form>
</HTML>
163
164
165
JavaScript Redirect
You're moving to a new domain name. You
have a time-delay in place on your download
site. You have a list of external web servers
that are helping to mirror your site. What
will help you deal and/or take advantage of
these situations? Javascript redirects will.
166
When a web page is moved will most
probably would like to place a "redirect" page
at the old location that informs the visitor of
the change and then after a timed delay, will
forward the visitor to the new location. With
the javascript redirection, you can do just
this.
167
Javascript Window.Location
The control over what page is loaded into the
browser rests in the javascript propety
window.location, by setting this equal to a
new URL you will in turn change from the
current web page to the one that is
specified. If you wanted to redirect all your
visitors to www.google.com when they
arrived at your site you would just need the
script below:
168
HTML & Javascript Code:
<script type="text/javascript">
window.location =
"http://www.google.com/" </script>
169
Javascript Time Delay
Implementing a timed delay in javascript is useful
for the following situations:
Showing an "Update your bookmark" page when you
have to change URLs or page locations
For download sites that wish to have a few second
delay before the page loads and when the download
starts
To refresh a web page every specified amount of
seconds
The code for this timed delay is slightly involved and
is beyond the scope of this tutorial. However, we
have tested it and it seems to function properly.
170
Redirect a web page
There are a couple of ways to redirect to another webpage with JavaScript. The
most popular ones are location.href and location.replace:
window.location.href = "http://www.w3schools.com";
// Simulate an HTTP redirect:
window.location.replace("http://www.w3schools.com");
The difference between href and replace, is that replace() removes the URL of
the current document from the document history, meaning that it is not
possible to use the "back" button to navigate back to the original document.
<html> <head>
<script type="text/javascript">
function delayer()
{ window.location = “tt.html" } </script> </head>
<body onLoad="setTimeout('delayer()', 5000)"> <h2
>Prepare to be redirected!</h2> <p>This page is a
time delay redirect, please update your bookmarks
to our new location!</p> </body> </html>
172
173
174
The most important part of getting the delay to
work is being sure to use the javascript function
setTimeout. We want the delayer() function be used
after 5 seconds or 5000 miliseconds, so we pass the
setTimeout() two arguments.
'delayer()' - The function we want setTimeout() to
execute after the specified delay.
5000 - the number of milisecods we want
setTimeout() to wait before executing our function.
1000 miliseconds = 1 second.
175
Web Page Redirection
Do use javascript for redirections when you
change your website's URL or move a file to a
new location. Don't use redirections when
they could easily be replaced with a normal
HTML hyperlink.
176
Javascript Popups
Chances are if you are reading this web page then
you have experienced hundreds of Javascript popup
windows throughout your web surfing lifetime. Want
to dish out some pain of your own creation onto
unsuspecting visitors? I hope not! Because web sites
with irrelevant popups are bad!
177
However, we will show you how to make
windows popup for reasonable occasions,
like when you want to display extra
information, or when you want to have
something open a new window that isn't
an HTML anchor tag <a>.
178
Javascript window.open Function
The window.open() function creates a new
browser window, customized to your
specifications, without the use of an HTML
anchor tag. In this example we will be
making a function that utilizes the
window.open() function.
179
<head> <script type="text/javascript"> function
myPopup()
{ window.open( “tt.html" ) }
</script> </head> <body> <form> <input
type="button" onClick="myPopup()" value="POP!">
</form> <p onClick="myPopup()">CLICK ME TOO!</p>
</body>
180
181
182
This works with pretty much any tag that
can be clicked on, so please go ahead an
experiment with this fun little tool.
183
Javascript Window.Open Arguments
There are three arguments that the
window.open function takes. First the
relative or absolute URL of the web page to
be opened. Secondly, a text name for the
window, and lastly a long string that contains
all the different properties of the window.
184
dependent - Subwindow closes if parent(the window
that opened it) window closes
fullscreen - Display browser in full screen mode
height - The height of the new window, in pixels
width - The width of the new window, in pixels
left - Pixel offset from the left side of the screen
top - Pixel offset from the top of the screen
resizable - Allow the user to resize the window or
prevent resizing
status - Display the status bar or not
185
Dependent, fullscreen, resizable, and
status are all examples of ON/OFF
properties. You can either set them
equal to zero to turn them off, or set
them to one to turn them ON. There is
no inbetween setting for these types of
properties
186
Upgraded Javascript Popup Window!
Now that we have the tools, let's make a
sophisticated Javascript popup window
that we can be proud of.
187
<head> <script type="text/javascript"> function
myPopup2()
{ window.open( “tt.html", "myWindow", "status = 0,
height = 300, width = 300, resizable = 0" ) }
</script> </head> <body> <form> <input
type="button" onClick="myPopup2()" value="POP2!">
</form> <p onClick="myPopup2()">CLICK ME
TOO!</p> </body>
188
189
190
<head> <script type="text/javascript"> function
myPopup2()
{ window.open( “tt.html", "myWindow", "status = 1,
height = 300, width = 300, resizable = 0" ) }
</script> </head> <body> <form> <input
type="button" onClick="myPopup2()" value="POP2!">
</form> <p onClick="myPopup2()">CLICK ME
TOO!</p> </body>
191
192
Now that is a prime example of a
worthless popup! When you make your
own, try to have them relate to your
content, like a small popup that has no
navigation that just gives the definition
or explanation of a word, sentence, or
picture!
193
Javascript Date and Time Object
The Date object is useful when you want to display a
date or use a timestamp in some sort of calculation.
In java you can either make a Date object by
supplying the date of your choice, or you can let
Javascript create a Date object based on your
visitor's system clock. It is usually best to let
Javascript simply use the system clock.
194
When creating a Date object based on the
computer's (not web server's!) internal clock, it is
important to note that if someone's clock is off by a
few hours or they are in a different time zone, then
the Date object will create a different time than the
one created with your own computer.
195
Javascript Date Today (Current)
To warm up our Javascript Date object skills,
let's do something easy. If you do not supply
any arguments to the Date constructor (this
makes the Date object) then it will create a
Date object based on the visitor's internal
clock.
196
<html>
<h4>It is now
<script type="text/javascript">
var currentTime = new Date()
document.write(currentTime )
</script> </h4>
</html>
197
198
Nothing shows up! That's because we still
don't know the methods of the Date
object that let us get the information we
need(i.e. Day, Month, Hour, etc).
199
Get the Javascript Time
The Date object has been created and now
we have a variable that holds the current
date. To get the information we need to print
out the date we have to utilize some or all of
the following functions
200
getTime() - Number of milliseconds since
1/1/1970 @ 12:00 AM
getSeconds() - Number of seconds (0-59)
getMinutes() - Number of minutes (0-59)
getHours() - Number of hours (0-23)
getDay() - Day of the week(0-6). 0 = Sunday, ... ,
6 = Saturday
getDate() - Day of the month (1-31)
getMonth() - Number of month (0-11)
getFullYear() - The four digit year (1970-9999)
201
<html>
<h4>It is now <script type="text/javascript">
var currentTime = new Date()
var month = currentTime.getMonth()
var day = currentTime.getDate()
var year = currentTime.getFullYear()
document.write(month + "/" + day + "/" +
year) </script> </h4>
</html>
202
203
Javascript Current Time Clock
Now instead of displaying the date we
will display the format you might see on
a typical digital clock HH:MM AM/PM (H =
Hour, M = Minute).
204
<html>
<h4>It is now <script type="text/javascript">
var currentTime = new Date()
var hours = currentTime.getHours()
var minutes = currentTime.getMinutes()
if (minutes < 10)
minutes = "0" + minutes
document.write(hours + ":" + minutes + " ")
if(hours > 11)
{ document.write("PM") }
else { document.write("AM") }
</script> </h4>
205
206
We check to see if hours or minutes is less
than 10, if it is then we need to add a zero to
the beginning of minutes. This is not
necessary, but if it is 1:01 AM then our clock
would output "1:1 AM", which doesn't look
very nice at all!
207
Javascript Form Validation
There's nothing more troublesome than receiving
orders, guestbook entries, or other form submitted
data that are incomplete in some way. You can avoid
these headaches once and for all with Javascript's
amazing way to combat bad form data with a
technique called "form validation".
208
The idea behind Javascript form validation
is to provide a method to check the user
entered information before they can even
submit it. Javascript also lets you display
helpful alerts to inform the user what
information they have entered incorrectly
and how they can fix it. In this lesson we
will be reviewing some basic form
validation, showing you how to check for
the following:
209
If a text input is empty or not
If a text input is all numbers
If a text input is all letters
If a text input is all alphanumeric characters (numbers &
letters)
If a text input has the correct number of characters in it
(useful when restricting the length of a username and/or
password)
If a selection has been made from an HTML select input
(the drop down selector)
If an email address is valid
How to check all above when the user has completed
filling out the form
210
Form Validation - Checking for Non-Empty
This has to be the most common type of
form validation. You want to be sure that
your visitors enter data into the HTML fields
you have "required" for a valid submission.
Below is the Javascript code to perform this
basic check to see if a given HTML input is
empty or not.
211
<html>
<head>
<script type='text/javascript'>
function check(form)
{
var valu=form.fname.value
if(valu==“”)
alert(“plz enter something”)
else
document.write(valu) }
</script>
</head>
<form>
Required Field: <input type='text' name=“fname">
<input type='button' onclick=check(this.form) value='Check
Field' />
</form>
212
215
216
Javascript document.getElementById
217
<html>
<head><script type="text/javascript">
function notEmpty()
{
var myTextField =document.getElementById('myText');
if(myTextField.value != "")
alert("You entered: " + myTextField.value)
else
alert("Would you please enter some text?")
} </script></head>
<input type='text' id='myText' >
<input type='button' onclick='notEmpty()' value='Form
Checker' />
</html>
218
219
220
221
Form Validation - Checking for Non-
Empty
222
<html><head>
<script type='text/javascript'>
function isEmpty(elem, helperMsg)
{ if(elem.value.length == 0)
{ alert(helperMsg);
return true; }
return false; }
</script></head>
<form> Required Field:
<input type='text' id='req1'/> <input type='button'
onclick="isEmpty(document.getElementById('req1’), 'Please
Enter a Value')" value='Check Field' /> </form>
223
224
225
226
<html><head>
<script type='text/javascript'>
function isEmpty(elem, helperMsg)
{ if(elem.value.length == 0)
{ alert(helperMsg);
elem.focus();
return true; }
return false; }
</script></head>
<form> Required Field:
<input type='text' id='req1'/> <input type='button'
onclick="isEmpty(document.getElementById('req1’), 'Please
Enter a Value')" value='Check Field' /> </form>
227
228
229
230
The function isEmpty will check to see that the
HTML input that we send it has something in it.
elem is a HTML text input that we send this
function. Javascriptstrings have built in
properties, one of which is the length property
which returns the length of the string. The chunk
of code elem.value will grab the string inside the
input and by adding on length elem.value.length
we can see how long the string is.
231
As long as elem.value.length isn't 0 then
it's not empty and we return true,
otherwise we send an alert to the user
with a helperMsg to inform them of their
error and return false
232
Form Validation - Checking for All
Numbers
233
Regular Expression(RegExp)
Character Meaning
/ backslash is an escape character in string literals.
Ex: /[a-z]s/I : an expression that searches for any letter in the range A-Z
followed by a whitespace character
^ Matches beginning of input
Ex: , /^A/ does not match the 'A' in "an A", but does match the 'A' in "An
E".
$ Matches end of input. For example, /t$/ does not match the 't' in "eater",
but does match it in "eat".
* Matches the preceding expression 0 or more times. Equivalent to {0,}. For
example, /bo*/ matches 'boooo' in "A ghost booooed" and 'b' in "A bird
warbled" but nothing in "A goat grunted".
+ Matches the preceding expression 1 or more times. Equivalent to {1,}.
For example, /a+/ matches the 'a' in "candy" and all the a's in
"caaaaaaandy", but nothing in "cndy".
? Matches the preceding expression 0 or 1 time. Equivalent to {0,1}.
(x) Matches 'x' and remembers the match, as the following example shows. The
parentheses are called capturing parentheses. The '(foo)' and '(bar)' in the pattern
/(foo) (bar) 1 2/ match and remember the first two words in the string "foo bar
foo bar".
(?:x) Matches 'x' but does not remember the match.
(?<=y)x Matches 'x' only if 'x' is followed by 'y'. This is called a lookahead.
x(?!y) Matches 'x' only if 'x' is not followed by 'y'. This is called a negated lookahead
(?<=y)x Matches x only if x is preceded by y. This is called a lookbehind.
x|y Matches 'x', or 'y' (if there is no match for 'x').
{n} Matches exactly n occurrences of the preceding expression. N must be a positive
integer.
{n,} Matches at least n occurrences of the preceding expression. N must be a positive
integer.
{n,m} Where n and m are positive integers and n <= m. Matches at least n and at most m
occurrences of the preceding expression. When m is omitted, it's treated as ∞.
[xyz] Character set. This pattern type matches any one of the characters in the brackets,
including escape sequences.
Sr.No
.
Expression & Description
1 [...]
Any one character between the brackets.
2 [^...]
Any one character not between the brackets.
3 [0-9]
It matches any decimal digit from 0 through 9.
4 [a-z]
It matches any character from lowercase a through
lowercase z.
5 [A-Z]
It matches any character from uppercase A through
uppercase Z.
6 [a-Z]
<html><head>
<script type='text/javascript'>
function isNumeric(elem, helperMsg){
var numericExpression = /^[0-9]+$/;
if(elem.value.match(numericExpression))
{ return true; }
else{ alert(helperMsg);
elem.focus();
return false;
} } </script></head>
<form> Numbers Only:
<input type='text' id='numbers'/> <input type='button'
onclick="isNumeric(document.getElementById('numbers'),
'Numbers Only Please')" value='Check Field' />
</form></html>
237
238
Form Validation - Checking
for All Letters
239
<html><head>
<script type='text/javascript'>
function isAlphabet(elem, helperMsg)
{ var alphaExp = /^[a-zA-Z]+$/;
if(elem.value.match(alphaExp))
{ return true; }
else{ alert(helperMsg);
elem.focus();
return false; } }
</script><head>
<form> Letters Only: <input type='text' id='letters'/> <input
type='button'
onclick="isAlphabet(document.getElementById('letters'),
'Letters Only Please')" value='Check Field' /> </form>
</html>
240
241
Form Validation - Checking for Numbers
and Letters
242
<html><head>
<script type='text/javascript'>
function isAlphabet(elem, helperMsg)
{ var alphaExp = /^[0-9a-zA-Z]+$/;
if(elem.value.match(alphaExp))
{ return true; }
else{ alert(helperMsg);
elem.focus();
return false; } }
</script><head>
<form> Letters Only: <input type='text' id='letters'/> <input
type='button'
onclick="isAlphabet(document.getElementById('letters'),
'Letters Only Please')" value='Check Field' /> </form>
</html>
243
244
Form Validation - Restricting the
Length
245
<html<<head>
<script type='text/javascript'> function
lengthRestriction(elem, min, max)
{ var uInput = elem.value;
if(uInput.length >= min && uInput.length <= max)
{ return true; }
else{
alert("Please enter between " +min+ " and " +max+ "
characters");
elem.focus();
return false; } }
</script></head>
<form> Username(6-8 characters):
<input type='text' id='restrict'/> <input type='button'
onclick="lengthRestriction(document.getElementById('restric
t'), 6, 8)" value='Check Field' /> </form> </html>
246
247
248
249
Form Validation - Selection Made
250
Form Validation - Selection Made
To be sure that someone has actually selected a choice from
an HTML select input you can use a simple trick of making
the first option as helpful prompt to the user and a red flag
to you for your validation code.
By making the first option of your select input something
like "Please Choose" you can spur the user to both make a
selection and allow you to check to see if the default option
"Please Choose" is still selected when the submit the form.
251
function madeSelection(elem, helperMsg)
{
if(elem.value == "Please Choose")
{
alert(helperMsg);
elem.focus();
return false;
}
else
{
return true;
} }
252
<html><head>
<script type='text/javascript'>
function madeSelection(elem, helperMsg)
{ if(elem.value == "Please Choose")
{ alert(helperMsg);
elem.focus();
return false; }
else{ return true; } }
</script><head>
<form> Selection: <select id='selection'> <option>Please
Choose</option>
<option>CA</option>
<option>WI</option>
<option>XX</option> </select>
<input type='button'
onclick="madeSelection(document.getElementById('selection'
), 'Please Choose Something')" value='Check Field' /> </form>
</html>
253
For e-mail
254
<script type='text/javascript'>
function emailValidator(elem, helperMsg){ var
emailExp = /^[w-.+]+@[a-zA-Z0-9.-]+.[a-
zA-z0-9]{2,4}$/; if(elem.value.match(emailExp)){
return true; }else{ alert(helperMsg);
elem.focus(); return false; } } </script> <form>
Email: <input type='text' id='emailer'/> <input
type='button'
onclick="emailValidator1(document.getElementBy
Id('emailer'), 'Not a Valid Email')" value='Check
Field' /> </form>
255
<html>
<head>
<script>
function validateForm() {
var x = document.forms["myForm"]["email"].value;
var atpos = x.indexOf("@");
var dotpos = x.lastIndexOf(".");
if (atpos<1 || dotpos<atpos+2 || dotpos+2>=x.length) {
alert("Not a valid e-mail address");
return false;
}
}
</script>
</head>
<body>
<form name="myForm" action="/action_page.php" onsubmit="return
validateForm();" method="post">
Email: <input type="text" name="email">
<input type="submit" value="Submit">
</form>
</body>
</html>
Event Object
257
<html>
<head>
<script type="text/javascript">
function show_coords(event)
{
x=event.clientX
y=event.clientY
alert("X coords: " + x + ", Y coords: " + y)
}</script></head>
<body onmousedown="show_coords(event)">
<p>Click in the document. An alert box will alert the x
and y coordinates of the mouse
pointer.</p></body></html>
258
259
<html>
<head>
<script type="text/javascript">
function whichButton(event)
{
alert(event.keyCode)
}
</script></head>
<body onkeyup="whichButton(event)">
<p><b>Note:</b> Make sure the right frame has focus when
trying this example!</p>
<p>Press a key on your keyboard. An alert box will alert the
unicode of the key pressed.</p>
</body>
</html>
260
261
<html>
<head>
<script type="text/javascript">
function isKeyPressed(event)
{
if (event.shiftKey==1)
{
alert("The shift key was pressed!")}
else
{ alert("The shift key was NOT pressed!")
}}</script></head>
<body onmousedown="isKeyPressed(event)">
<p>Click somewhere in the document. An alert box will tell
you if you pressed the shift key or not.</p>
</body></html>
262
263
<html><head>
<script type="text/javascript">
function getEventType(event)
{
alert(event.type);
}
</script></head>
<body onmousedown="getEventType(event)">
<p>Click in the document.
An alert box will tell what type of event
that was triggered.</p>
</body>
</html>
264
265
DO IT
266
Directly Executing Javascript
in a Browser
267
<html>
<a href="javascript: alert('News
Flash!')">News Flash</a>
</html>
268
269
Simple Javscript Void 0 Simple Example
270
<html>
<a href="javascript: void(0)">I am a
useless link</a>
</html>
271
272
Simple Javscript Void 0 Useful Example
273
<html>
<a href="javascript:
void(myNum=10);alert('myNum =
'+myNum)">
Set myNum Please</a>
</html> 274
275
OBJECT IN JAVASCRIPT
276
Window
Frame
History
Location
document
form
text
Built-in Objects
Array
Date
String 277
String object
length()
278
<html>
<body>
<script type="text/javascript">
var txt="Hello World!"
document.write(txt.length)
</script>
</body>
</html>
279
12
280
<html><body><script type="text/javascript">
var txt="Hello World!"
document.write("<p>Big: " + txt.big() + "</p>")
document.write("<p>Small: " + txt.small() + "</p>")
document.write("<p>Bold: " + txt.bold() + "</p>")
document.write("<p>Italic: " + txt.italics() + "</p>")
document.write("<p>Blink: " + txt.blink() + " (does not work in IE)</p>")
document.write("<p>Fixed: " + txt.fixed() + "</p>")
document.write("<p>Strike: " + txt.strike() + "</p>")
document.write("<p>Fontcolor: " + txt.fontcolor("Red") + "</p>")
document.write("<p>Fontsize: " + txt.fontsize(16) + "</p>")
document.write("<p>Lowercase: " + txt.toLowerCase() + "</p>")
document.write("<p>Uppercase: " + txt.toUpperCase() + "</p>")
document.write("<p>Subscript: " + txt.sub() + "</p>")
document.write("<p>Superscript: " + txt.sup() + "</p>")
document.write("<p>Link: " + txt.link("http://www.w3schools.com") +
"</p>")
</script></body></html>
281
282
indexOf()
283
<html>
<body>
<script type="text/javascript">
var str="Hello world!"
document.write(str.indexOf("Hello") + "<br />")
document.write(str.indexOf("World") + "<br />")
document.write(str.indexOf("world"))
</script>
</body>
</html> 284
285
replace()
286
<html>
<body>
<script type="text/javascript">
var str="Visit Microsoft!"
document.write(str.replace(/Microsoft/,“IMS"
))
</script>
</body>
</html>
287
288
Math object
289
<html>
<body>
<script type="text/javascript">
document.write(Math.round(0.60) + "<br />")
document.write(Math.round(0.50) + "<br />")
document.write(Math.round(0.49) + "<br />")
document.write(Math.round(-4.40) + "<br />")
document.write(Math.round(-4.60))
</script>
290
291
<html>
<body>
<script type="text/javascript">
document.write(Math.random())
</script>
292
293
<html>
<body>
<script type="text/javascript">
document.write(Math.max(5,7) + "<br />")
document.write(Math.max(-3,5) + "<br />")
document.write(Math.max(-3,-5) + "<br />")
document.write(Math.max(7.25,7.30))
</script></body>
</html>
294
295
<html>
<body>
<script type="text/javascript">
document.write(Math.min(5,7) + "<br />")
document.write(Math.min(-3,5) + "<br />")
document.write(Math.min(-3,-5) + "<br />")
document.write(Math.min(7.25,7.30))
</script></body>
</html>
296
297
<html>
<body>
<script type="text/javascript">
document.write(Math.abs(7.25) + "<br />")
document.write(Math.abs(-7.25))
</script>
298
299
Window object
300
<html>
<body>
<script type="text/javascript">
myWindow=window.open('','','width=200,height=100')
myWindow.document.write("This is 'myWindow'")
myWindow.focus()
</script>
</body>
301
302
<html>
<head>
<script type="text/javascript">
function closeWin()
{ myWindow.close()}
</script></head><body>
<script type="text/javascript">
myWindow=window.open('','','width=200,height=100')
myWindow.document.write("This is 'myWindow'")
</script>
<input type="button" value="Close 'myWindow'"
onclick="closeWin()" />
</body>
</html>
303
304
<html> <head>
<script type="text/javascript">
function goBack() { window.history.back()
}
</script> </head>
<body><input type="button" value="Back"
onclick="goBack()" /></body> </html>
305
306
The go() method loads a specific page in
the history list.
Syntax
history.go(number|URL)
307
<html> <head>
<script type="text/javascript">
function goBack()
{
window.history.go(-1)
} </script> </head>
<body>
<input type="button" value="Back" onclick="goBack()"
>
</body> </html>
308
Examples
309
<HTML>
<HEAD>
<TITLE>JavaScript Example</TITLE>
</HEAD><BODY>
<CENTER>
<FORM><INPUT TYPE="button" VALUE="silver"
ONCLICK="document.bgColor='silver'">
<INPUT TYPE="button" VALUE="slate"
ONCLICK="document.bgColor='lightslategray'">
<INPUT TYPE="button" VALUE="green"
ONCLICK="document.bgColor='lightgreen'">
<INPUT TYPE="button" VALUE="blue"
ONCLICK="document.bgColor='lightblue'">
<INPUT TYPE="button" VALUE="white"
ONCLICK="document.bgColor='white'">
</FORM></BODY></HTML> 310
311
312
313
Example 2
314
<html><head>
<script type="text/javascript" language="JavaScript">
function handler(c){
c.checked = true;
return 0 }
</script></head>
<form name="formA" action="javascript:void(0)">
<textarea rows="10" cols="45"
onclick="handler(formA.click)"
onmouseover="handler(formA.over)"></textarea>
<br><br>
Click<input type="checkbox" name="click">&nbsp;
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;MouseOver<input
type="checkbox" name="over">
</form></html>
315
316
Example 3
317
<html><head>
<script type="text/javascript" language="JavaScript">
function handler(c,t,s) {
t.value=s
c.checked = true;
return 0 }</script></head>
<form name="formA" action="javascript:void(0)">
<textarea rows="10" cols="45"
onclick="handler(formA.click,formB.t1,'click')"
onmouseover="handler(formA.over,formB.t1,'mouseover')"></textarea><b
r><br>
Click<input type="checkbox" name="click">&nbsp;
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;MouseOver<input type="checkbox"
name="over">
</form>
<form name="formB">
<textarea name="t1" rows="8" cols="45" wrap='soft'></textarea>
</html>
318
319
Example 4
320
<htrml><head>
<script type="text/javascript" language="JavaScript">
function handler(t,c,s)
{
t.value += s;
c.checked = true;
return 0
}
</script>
</head>
<form name="formA" action="javascript:void(0)"
onreset= "handler(formB.t1, formB.reset, 'reset ')"
onsubmit="handler(formB.t1, formB.submit, 'submit ')">
<textarea rows="4" cols="45" wrap="soft"
321
ondblclick= "handler(formB.t1, formB.dblclick, 'dblclick ')"
onmouseover="handler(formB.t1, formB.over, 'over ')"
onmouseout= "handler(formB.t1, formB.out, 'out ')" >
Move the mouse, click and type here. Try selecting text.
</textarea>
<input type="Reset"> <input type="Submit" value="Submit">
</form>
<form name="formB">
<textarea name="t1" rows="8" cols="45" wrap="soft"></textarea>
click:<input type="checkbox" name="click">
</form>
322
323
Example 5
324
<html><head>
<script type="text/javascript">
txtsize=0
maxsize=100
function writemsg()
{if (txtsize<maxsize) {
document.getElementById('msg').style.fontSize=txtsize
txtsize++
timer=setTimeout("writemsg()",10) }}
function stoptimer()
{clearTimeout(timer)}
325
326
Example 6
327
<html><head><script type="text/javascript">
function newColor(color)
{document.getElementById('x').style.background=color}
</script></head><body>
<p>This example demonstrates how to change
the background color of a textarea.</p>
<p>Mouse over the three colored table cells,
and the textarea will change color:</p>
<table width="100%"><tr>
<td bgcolor="red"
onmouseover="newColor('red')">&nbsp;</td>
<td bgcolor="blue"
onmouseover="newColor('blue')">&nbsp;</td>
<td bgcolor="green"
328
329
<html><head>
<script language=javascript type="text/javascript">
x = "This text will scroll to the left slowly! ... "
x = x + x
i = 0
function scroll(){
window.defaultStatus=x.substring(i,x.length) + x
i++
if (i==x.length)
i=0 ;
tid=setTimeout("scroll()", 100)
}
y=" "
function stopScroll(){
window.defaultStatus=" "
window.clearTimeout(tid);
330
331
<html><head><script language=javascript type="text/javascript">
var plus,minus,divide,times
function initialise(){
plus=document.calc.operator.options[0]
minus=document.calc.operator.options[1]
divide=document.calc.operator.options[2]
times=document.calc.operator.options[3]}
function calculate(){
x = parseInt(document.calc.val1.value)
y = parseInt(document.calc.val2.value)
if (plus.selected)
document.calc.answer.value=x + y
if (minus.selected)
document.calc.answer.value=x - y
332
<body onLoad="initialise()">
<h2>Calculator</h2>
<form name="calc" action="post">
<input type=text name=val1 size=10>
<select name=operator><option value=plus>+
<option value=minus>-<option value=divide>/
<option value=times>*</select>
<input type=text name=val2 size=10>=
<input type=text name=answer size=10>
<input type=button value=answer onClick="calculate()">
</form</body></html>
333
334
Changing Text with innerHTML
335
<html><head>
<script type="text/javascript">
function changeText()
{ document.getElementById('boldStuff').innerHTML =
‘ATUL KAHATE'; }
</script></head> <body>
<form>
<p>Welcome to the site <b id='boldStuff'>dude</b>
</p> <input type='button' onclick='changeText()'
value='Change Text'/>
</form> </body> </html>
336
337
338
Updating Text Based on User Input
339
<script type="text/javascript">
function changeText2()
{
var userInput = document.getElementById('userInput').value;
document.getElementById('boldStuff2').innerHTML = userInput; }
</script>
<p>Welcome to the site <b id='boldStuff2'>dude</b> </p>
<input type='text' id='userInput' value='Enter Text Here'> <input
type='button' onclick='changeText2()' value='Change Text'/>
340
341
342
<html>
<head>
<script type="text/javascript">cc=0
function changeimage()
{If (cc==0)
{cc=1
document.getElementById('myimage').src="bulbon.gif"
}else
{cc=0
document.getElementById('myimage').src="bulboff.gif"
343
344
345
DHTML WITH JAVASCRIPT
346
DHTML is NOT a W3C Standard
DHTML stands for Dynamic HTML.
DHTML is not a standard defined by the World Wide Web
Consortium (W3C). DHTML is a "marketing term" - used by
Netscape and Microsoft to describe the new technologies
the 4.x generation browsers would support.
DHTML is a combination of technologies used to create
dynamic Web sites.
To most people DHTML means a combination of HTML 4.0,
Style Sheets and JavaScript.
W3C once said: "Dynamic HTML is a term used by some
347
DHTML CSS Positioning
348
<html><head><style>
h1.ex1{
position:relative;
left:20px;}
h1.ex2{
position:relative;
left:-20px;}
</style></head><body>
<h1>Normal Heading</h1>
<h1 class="ex1">Heading +20</h1>
<h1 class="ex2">Heading -20</h1>
<p>
Relative positioning moves an element relative to its original position.
349
350
<html><head><style>
h1.x{
position:absolute;
left:100px;
top:150px;
}</style></head><body>
<h1 class="x">This is a heading</h1>
<p>With absolute positioning, an element can be placed
anywhere on a page.</p>
<p>The LEFT position of the heading is 100 pixels from the
left of the page.
The TOP position is 150 pixels from the top of the
351
352
DHTML Document Object Model
353
<html>
<body>
<h1 id="header">My header</h1>
<script type="text/javascript">
document.getElementById('header').style.color="red"
</script>
<p><b>Note:</b> It is the script that changes the
style of the element!</p>
</body></html>
354
355
DHTML Event Handlers
356
<html>
<body>
<h1 onmouseover="style.color='red'"
onmouseout="style.color='black'">
Mouse over this text</h1>
</body>
357
358
<html><body>
<p>Move the mouse over the words to see the cursor change</p>
<span style="cursor: auto">Auto</span><br />
<span style="cursor: crosshair">Crosshair</span><br />
<span style="cursor: default">Default</span><br />
<span style="cursor: pointer">Pointer</span><br />
<span style="cursor: hand">Hand</span><br />
<span style="cursor: move">Move</span><br />
<span style="cursor: e-resize">e-resize</span><br />
<span style="cursor: ne-resize">ne-resize</span><br />
<span style="cursor: nw-resize">nw-resize</span><br />
<span style="cursor: n-resize">n-resize</span><br />
<span style="cursor: se-resize">se-resize</span><br />
<span style="cursor: sw-resize">sw-resize</span><br />
<span style="cursor: s-resize">s-resize</span><br />
<span style="cursor: w-resize">w-resize</span><br />
<span style="cursor: text">text</span><br />
<span style="cursor: wait">wait</span><br />
<span style="cursor: help">help</span><br />
</body></html>
359
360
<html>
<body>
<h1 onmouseover="style.color='red'"
onmouseout="style.color='black'">
Mouse over this text</h1>
</body>
</html>
361
362
<html><head><script type="text/javascript">
function blinking_header()
{
if (!document.getElementById('blink').style.color)
{document.getElementById('blink').style.color="red" }
if (document.getElementById('blink').style.color=="red")
{document.getElementById('blink').style.color="black"}
else{document.getElementById('blink').style.color="red"}
timer=setTimeout("blinking_header()",100)}
function stoptimer(){clearTimeout(timer)}
363
364
<html><head><script type="text/javascript">
function moveleft()
{document.getElementById('image').style.position="a
bsolute"
document.getElementById('image').style.left="0"}
function moveback()
{document.getElementById('image').style.position="r
elative"}
</script></head>
365
366
<html><head><script>
function startEQ()
{richter=5
parent.moveBy(0,richter)
parent.moveBy(0,-richter)
parent.moveBy(richter,0)
parent.moveBy(-richter,0)
timer=setTimeout("startEQ()",10)}
function stopEQ()
{clearTimeout(timer)}
367
368
<html><head>
<script type="text/javascript">
var i=0
txt=new Array("trailA","trailB","trailC")
function cursor(interval){
pos=i*8+5
if (interval=='first'){i=0}
if (i==0){
xpos=event.clientX
ypos=event.clientY
document.all(txt[i]).style.visibility="visible
"
document.all(txt[i]).style.position="absolu
te"
document.all(txt[i]).style.left=xpos+5
document.all(txt[i]).style.top=ypos+5 }
369
370
<html><head><script type="text/javascript">
var c=0
var t
function timedCount()
{
document.getElementById('txt').value=c
c=c+1
t=setTimeout("timedCount()",1000)
}
function stopCount()
{
clearTimeout(t)
}
</script></head><body><form>
371
Unit 4 Java script.pptx

More Related Content

Similar to Unit 4 Java script.pptx

Javascript - Ebook (A Quick Guide)
Javascript - Ebook (A Quick Guide)Javascript - Ebook (A Quick Guide)
Javascript - Ebook (A Quick Guide)sourav newatia
 
WEB PROGRAMMING UNIT II BY BHAVSINGH MALOTH
WEB PROGRAMMING UNIT II BY BHAVSINGH MALOTHWEB PROGRAMMING UNIT II BY BHAVSINGH MALOTH
WEB PROGRAMMING UNIT II BY BHAVSINGH MALOTHBhavsingh Maloth
 
Web programming UNIT II by Bhavsingh Maloth
Web programming UNIT II by Bhavsingh MalothWeb programming UNIT II by Bhavsingh Maloth
Web programming UNIT II by Bhavsingh MalothBhavsingh Maloth
 
Basics java scripts
Basics java scriptsBasics java scripts
Basics java scriptsch samaram
 
Javascript
JavascriptJavascript
JavascriptSushma M
 
JavaScript - Getting Started.pptx
JavaScript - Getting Started.pptxJavaScript - Getting Started.pptx
JavaScript - Getting Started.pptxJonnJorellPunto
 
&lt;img src="../i/r_14.png" />
&lt;img src="../i/r_14.png" />&lt;img src="../i/r_14.png" />
&lt;img src="../i/r_14.png" />tutorialsruby
 
Essential_Javascript_--_A_Javascript_Tutorial
Essential_Javascript_--_A_Javascript_TutorialEssential_Javascript_--_A_Javascript_Tutorial
Essential_Javascript_--_A_Javascript_Tutorialtutorialsruby
 
Essential Javascript -- A Javascript &lt;b>Tutorial&lt;/b>
Essential Javascript -- A Javascript &lt;b>Tutorial&lt;/b>Essential Javascript -- A Javascript &lt;b>Tutorial&lt;/b>
Essential Javascript -- A Javascript &lt;b>Tutorial&lt;/b>tutorialsruby
 
Essential_Javascript_--_A_Javascript_Tutorial
Essential_Javascript_--_A_Javascript_TutorialEssential_Javascript_--_A_Javascript_Tutorial
Essential_Javascript_--_A_Javascript_Tutorialtutorialsruby
 
Session vii(java scriptbasics)
Session vii(java scriptbasics)Session vii(java scriptbasics)
Session vii(java scriptbasics)Shrijan Tiwari
 
2javascript web programming with JAVA script
2javascript web programming with JAVA script2javascript web programming with JAVA script
2javascript web programming with JAVA scriptumardanjumamaiwada
 
Introduction to Javascript
Introduction to JavascriptIntroduction to Javascript
Introduction to Javascriptambuj pathak
 
Basic Java script handouts for students
Basic Java script handouts for students Basic Java script handouts for students
Basic Java script handouts for students shafiq sangi
 
What is java script
What is java scriptWhat is java script
What is java scriptsumanbaba_73
 

Similar to Unit 4 Java script.pptx (20)

Javascript - Ebook (A Quick Guide)
Javascript - Ebook (A Quick Guide)Javascript - Ebook (A Quick Guide)
Javascript - Ebook (A Quick Guide)
 
WEB PROGRAMMING UNIT II BY BHAVSINGH MALOTH
WEB PROGRAMMING UNIT II BY BHAVSINGH MALOTHWEB PROGRAMMING UNIT II BY BHAVSINGH MALOTH
WEB PROGRAMMING UNIT II BY BHAVSINGH MALOTH
 
Web programming UNIT II by Bhavsingh Maloth
Web programming UNIT II by Bhavsingh MalothWeb programming UNIT II by Bhavsingh Maloth
Web programming UNIT II by Bhavsingh Maloth
 
Javascript
JavascriptJavascript
Javascript
 
Basics java scripts
Basics java scriptsBasics java scripts
Basics java scripts
 
Javascript
JavascriptJavascript
Javascript
 
Introduction to JavaScript
Introduction to JavaScriptIntroduction to JavaScript
Introduction to JavaScript
 
web designing course bangalore
web designing course bangaloreweb designing course bangalore
web designing course bangalore
 
JavaScript - Getting Started.pptx
JavaScript - Getting Started.pptxJavaScript - Getting Started.pptx
JavaScript - Getting Started.pptx
 
&lt;img src="../i/r_14.png" />
&lt;img src="../i/r_14.png" />&lt;img src="../i/r_14.png" />
&lt;img src="../i/r_14.png" />
 
Essential_Javascript_--_A_Javascript_Tutorial
Essential_Javascript_--_A_Javascript_TutorialEssential_Javascript_--_A_Javascript_Tutorial
Essential_Javascript_--_A_Javascript_Tutorial
 
Essential Javascript -- A Javascript &lt;b>Tutorial&lt;/b>
Essential Javascript -- A Javascript &lt;b>Tutorial&lt;/b>Essential Javascript -- A Javascript &lt;b>Tutorial&lt;/b>
Essential Javascript -- A Javascript &lt;b>Tutorial&lt;/b>
 
Essential_Javascript_--_A_Javascript_Tutorial
Essential_Javascript_--_A_Javascript_TutorialEssential_Javascript_--_A_Javascript_Tutorial
Essential_Javascript_--_A_Javascript_Tutorial
 
Session vii(java scriptbasics)
Session vii(java scriptbasics)Session vii(java scriptbasics)
Session vii(java scriptbasics)
 
Java scipt
Java sciptJava scipt
Java scipt
 
Introduction to Java Scripting
Introduction to Java ScriptingIntroduction to Java Scripting
Introduction to Java Scripting
 
2javascript web programming with JAVA script
2javascript web programming with JAVA script2javascript web programming with JAVA script
2javascript web programming with JAVA script
 
Introduction to Javascript
Introduction to JavascriptIntroduction to Javascript
Introduction to Javascript
 
Basic Java script handouts for students
Basic Java script handouts for students Basic Java script handouts for students
Basic Java script handouts for students
 
What is java script
What is java scriptWhat is java script
What is java script
 

Recently uploaded

"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...Zilliz
 
Platformless Horizons for Digital Adaptability
Platformless Horizons for Digital AdaptabilityPlatformless Horizons for Digital Adaptability
Platformless Horizons for Digital AdaptabilityWSO2
 
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Victor Rentea
 
FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024The Digital Insurer
 
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWEREMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWERMadyBayot
 
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdfRising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdfOrbitshub
 
Introduction to Multilingual Retrieval Augmented Generation (RAG)
Introduction to Multilingual Retrieval Augmented Generation (RAG)Introduction to Multilingual Retrieval Augmented Generation (RAG)
Introduction to Multilingual Retrieval Augmented Generation (RAG)Zilliz
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingEdi Saputra
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FMESafe Software
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAndrey Devyatkin
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyKhushali Kathiriya
 
JohnPollard-hybrid-app-RailsConf2024.pptx
JohnPollard-hybrid-app-RailsConf2024.pptxJohnPollard-hybrid-app-RailsConf2024.pptx
JohnPollard-hybrid-app-RailsConf2024.pptxJohnPollard37
 
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamDEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamUiPathCommunity
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDropbox
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
Exploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusExploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusZilliz
 
Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxRustici Software
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc
 
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...apidays
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherRemote DBA Services
 

Recently uploaded (20)

"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
 
Platformless Horizons for Digital Adaptability
Platformless Horizons for Digital AdaptabilityPlatformless Horizons for Digital Adaptability
Platformless Horizons for Digital Adaptability
 
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
 
FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024
 
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWEREMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
 
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdfRising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
 
Introduction to Multilingual Retrieval Augmented Generation (RAG)
Introduction to Multilingual Retrieval Augmented Generation (RAG)Introduction to Multilingual Retrieval Augmented Generation (RAG)
Introduction to Multilingual Retrieval Augmented Generation (RAG)
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : Uncertainty
 
JohnPollard-hybrid-app-RailsConf2024.pptx
JohnPollard-hybrid-app-RailsConf2024.pptxJohnPollard-hybrid-app-RailsConf2024.pptx
JohnPollard-hybrid-app-RailsConf2024.pptx
 
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamDEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor Presentation
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Exploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusExploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with Milvus
 
Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptx
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 

Unit 4 Java script.pptx

  • 2. 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. 2
  • 3. JavaScript has been around for several years now, in many different flavors. The main benefit of Javascript is to add additional interaction between the web site and its visitors at the cost of a little extra work by the web developer. Javascript allows industrious web masters to get more out of their website than HTML and CSS can provide. 3
  • 4. By definition, Javascript is a client-side scripting language. This means the web surfer's browser will be running the script. This is opposite to client-side is server-side, which occurs in a language like PHP. These PHP scripts are run by the web hosting server. There are many uses (and abuses!) for the powerful Javascript language. Here are a few things that you may or may not have seen in your web surfing days. 4
  • 5. Example of java scripts: Clocks Mouse Trailers (an animation that follows your mouse when you surf a site) Drop Down Menus Alert Messages Popup Windows Html form Data Validation 5
  • 6. Advantages of JavaScript Less server interaction − You can validate user input before sending the page off to the server. This saves server traffic, which means less load on your server. Immediate feedback to the visitors − They don't have to wait for a page reload to see if they have forgotten to enter something. Increased interactivity − You can create interfaces that react when the user hovers over them with a mouse or activates them via the keyboard. Richer interfaces − You can use JavaScript to include such items as drag-and-drop components and sliders to give a Rich Interface to your site visitors.
  • 7. Limitations of JavaScript We cannot treat JavaScript as a full-fledged programming language. It lacks the following important features − • 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 multi-threading or multiprocessor capabilities.
  • 8. Syntax of Java Script JavaScript can be implemented using JavaScript statements that are placed within the <script>... </script> HTML tags in a web page. 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> The script tag takes two important attributes − 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". So your JavaScript segment will look like − <script language = "javascript" type = "text/javascript"> JavaScript code </script>
  • 9. Whitespace and Line Breaks JavaScript ignores spaces, tabs, and newlines that appear in JavaScript programs. Semicolons are Optional Simple statements in JavaScript are generally followed by a semicolon character, just as they are in C, C++, and Java. JavaScript, however, allows you to omit this semicolon if each of your statements are placed on a separate line. For example, the following code could be written without semicolons. <script language = "javascript" type = "text/javascript"> <!-- var1 = 10 var2 = 20 //--> </script> But when formatted in a single line as follows, you must use semicolons − <script language = "javascript" type = "text/javascript"> <!-- var1 = 10; var2 = 20; //--> </script>
  • 10. Case Sensitivity JavaScript is a case-sensitive language. This means that the language keywords, variables, function names, and any other identifiers must always be typed with a consistent capitalization of letters. So the identifiers Time and TIME will convey different meanings in JavaScript. Comments in JavaScript JavaScript supports both C-style and C++-style comments, Thus − • Any text between a // and the end of a line is treated as a comment and is ignored by JavaScript. • Any text between the characters /* and */ is treated as a comment. This may span multiple lines. • JavaScript also recognizes the HTML comment opening sequence <!--. JavaScript treats this as a single-line comment, just as it does the // comment. • The HTML comment closing sequence --> is not recognized by JavaScript so it should be written as //-->.
  • 11. Example The following example shows how to use comments in JavaScript. <script language = "javascript" type = "text/javascript"> <!-- // This is a comment. It is similar to comments in C++ /* * This is a multi-line comment in JavaScript * It is very similar to comments in C Programming */ //--> </script>
  • 12. How To Write Javascript If you have ever used CSS before, then the whole part about how to include Javascript will be a lot simpler to grasp. Here are three important steps you should always take when creating or using someone else's Javascript code. 12
  • 13. Use the script tag to tell the browser you are using Javascript. Write or download some Javascript Test the script! There are so many different things that can go wrong with a script, be it human error, browser compatability issues, or operating system differences. So whenever using Javascript, be sure that you test your script out on a wide variety of systems and most importantly, different web browsers. 13
  • 14. Your First Javascript Script To follow the classic examples of many programming let's use Javascript to print out "Hello World" to the browser. I know this isn't very interesting, but it will be a good way to explain all the overhead required to do something in Javascript 14
  • 15. HTML & JavaScript Code: <html> <body> <script type="text/javascript"> document.write("Hello World!") </script> </body> </html> 15
  • 16. Our first step was to tell the browser we were using a script with <script> tag. Next we set the type of script equal to "text/javascript", which you may notice that doing this is similar to the way you specify CSS, which is "text/css". Next we added an optional HTML comment that surrounds our Javascript code. If a browser does not support Javascript, then it will not display our code in plain text to the user! The comment was ended with a "//-->" because "//" signifies a comment in Javascript, so we add that to prevent a browser from reading the end of the HTML comment in as a piece of Javascript code. 16
  • 17. Javascript document.write The final step of our script was to use a function called document.write which writes a string into our HTML document. document.write can be used to write text, HTML, or a little of both. We passed the famous string of text to the function to spell out "Hello World!" which it printed to the screen. 17
  • 18. Syntax Looking at our Javascript code above, notice that there is no semicolon at the end of the statement "document.write(Hello World!)". Why? Because Javascript does not require that you use semicolons to signify the end of each statement. If you are an experienced programmer and prefer to use semicolons, feel free to do so. Javascript will not malfunction from ending semicolons. The only time it is necessary to use a semicolon is when you choose to smash two statements onto one line(i.e. two document.write statements on one line). 18
  • 19. Javascript - Is it Enabled? This lesson will first teach you how to enable Javascript in Internet Explorer then show you how you can write a very simple script to separate those who don't have Javascript enabled from those that do on your websites. 19
  • 20. Enable Javascript - Internet Explorer In Internet Explorer 6/7 (download Internet Explorer) you can check to see if Javascript is enabled by navigating to the custom security settings that are somewhat buried (don't worry we'll help you find it). Click on the Tools menu Choose the Internet Options... from the menu Click the Security tab on the Internet Options pop up Click the Custom Level... button to access your security settings Scroll almost all the way down to the Scripting section Select the Enable button for Active scripting Click OK to finish the process Click Yes when asked to confirm 20
  • 21. Javascript Detection These days it's basically impossible to navigate the web without a Javascript enabled browser, so checking whether or not a user has Javascript enabled is not all that important. Chances are the only way it be disabled is if the company's IT staff has decided to disable Javascript for some reason. However, if you still want to be sure your users are Javascript enabled, this script will get it done 21
  • 22. The only sure fire way to separate users that don't have Javascript from those that do is to use a simple redirect script that will only work for those with Javascript enabled. If a person's browser does not have Javascript enabled the script will not run and they will remain on the same page. 22
  • 24. Where to Place Javascript There are three general areas that Javascript can be placed for use in a web page. 24
  • 25. Inside the head tag Within the body tag In an external file The location choice of head or body is very simple. If you want to have a script run on some event, such as when a user clicks somewhere, then you will place that script in the head. If you want the script to run when the page loads, like our "Hello World!" example , then you will want to place the script within the body tag. 25
  • 26. An Example Head Script Since we have already seen the kind of script that goes in the body, how about we write a script that takes place when some event occurs, say a click on a button. 26
  • 27. HTML & JavaScript Code: <html> <head> <script type="text/javascript"> function popup() { document.write("Hello World!") } </script> </head> <body> <input type="button" onclick="popup()" value="popup"> </body> </html> 27
  • 28. 28
  • 29. 29
  • 30. We created a function called popup and placed it in the head of the HTML document. Now every time someone clicks on the button (this is an event) "Hello World!“ will be display. We will go into more depth on functions and events in a later . 30
  • 31. External Javascript Files Having already dicussed placing Javascript in the head and body of your HTML document, let us now explore the third possible location, an external file. 31
  • 32. Importing an External Javascript File Importing an external file is relatively painless. First the file you are importing must be valid Javascript, and only Javascript. Second, the file must have the extension ".js". Lastly, you must know the location of the file. Let us assume we have a file "myjs.js" that contains a one line Hello World alert function. Also, let us assume that the file is the same directory as our HTML file we are going to code up. To import the file you would do the following in your HTML document. 32
  • 33. HTML & JavaScript Code: <html> <head> <script src="myjs.js"> </script> </head> <body> <input type="button" onclick="popup()" value="Click Me!"> </body> </html> 33
  • 35. 35
  • 36. 36
  • 37. 37
  • 38. Great Javascript Repositories There is a ton of great stuff you can do with Javascript, if you know how to code like Paul Allen and Bill Gates, but for the rest of us it is nice to get incredible Javascript tools without having to write them ourselves. Below are some of the better Javascript resources on the web these days. JavaFile.com Java-Scripts.com 38
  • 39. External File Tips & Recap Use external Javascript files when you want to use the same script on many pages, but don't want to have to rewrite the code on every page! Use external Javascript files for including both types of scripts! The type that you place in the head (functions) and the type you place in the body (scripts you want to run when the page loads). Be sure that your Javascript files (.js) do not include the <script> tag. They should only have the HTML comment and Javascript code. 39
  • 40. Javascript Operators Operators in Javascript are very similar to operators that appear in other programming languages. The definition of an operator is a symbol that is used to perform an operation. Most often these operations are arithmetic (addition, subtraction, etc), but not always. 40
  • 42. Operator English Example + Addition 2 + 4 - Subtraction 6 - 2 * Multiplication 5 * 3 / Division 15 / 3 % Modulus 43 % 10 42
  • 43. Assignment operator Operator Example Same As = x = y x = y += x += y x = x + y -= x -= y x = x - y *= x *= y x = x * y /= x /= y x = x / y %= x %= y x = x % y **= x **= y x = x ** y
  • 44. Javascript Operator Example with Variables Performing operations on variables that contain values is very common and easy to do. Below is a simple script that performs all the basic arithmetic operations 44
  • 45. <html> <body> <script type="text/javascript"> var two=2 var ten=10 document.write("two + ten = ") result=two + ten document.write(result) </script> </body> <html> 45
  • 46. 46
  • 47. <html> <body> <script type="text/javascript"> var two=2 var ten=10 document.write("two - ten = ") result=two - ten document.write(result) </script> </body> <html> 47
  • 48. 48
  • 49. Comparison Operators Comparisons are used to check the relationship between variables and/or values. A single equal sign sets a value while a double equal sign (==) compares two values. Comparison operators are used inside conditional statements and evaluate to either true or false. 49
  • 50. Operator English Example Result == Equal To x == y false != Not Equal To x != y true < Less Than x < y true > Greater Than x > y false <= Less Than or Equal To x <= y true >= Greater Than or Equal To x >= y false 50
  • 51. Logical operator Operator Description && logical and || logical or ! logical not String Operator:The + operator can also be u to add (concatenate) strings.
  • 52. Type operator Operator Description typeof Returns the type of a variable instanceof Returns true if an object is an instance of an object type
  • 53. Bitwise operator Operator Descriptio n Example Same as Result Decimal & AND 5 & 1 0101 & 0001 0001 1 | OR 5 | 1 0101 | 0001 0101 5 ~ NOT ~ 5 ~0101 1010 10 ^ XOR 5 ^ 1 0101 ^ 0001 0100 4 << Zero fill left shift 5 << 1 0101 << 1 1010 10 >> Signed right shift 5 >> 1 0101 >> 1 0010 2 >>> Zero fill right shift 5 >>> 1 0101 >>> 1 0010 2
  • 54. JavaScript Variables Variables in Javascript behave the same as variables in most popular programming languages (C, C++, etc) except that you don't have to declare variables before you use them. If you don't know what declaring is, don't worry about it, it isn't important! 54
  • 55. Javascript Using Variables A variable's purpose is to store information so that it can be used later. A variable is a symbolic name that represents some data that you set. To think of a variable name in real world terms, picture that the name is a grocery bag and the data it represents are the groceries. The name wraps up the data so you can move it around a lot easier, but the name is not the data! 55
  • 56. A Variable Example When using a variable for the first time it is not necessary to use "var" before the variable name, but it is a good programming practice to make it crystal clear when a variable is being used for the first time in the program. Here we are showing how the same variable can take on different values throughout a script 56
  • 57. <body> <script type="text/javascript"> var linebreak = "<br />“ var my_var = "Hello World!“; document.write(my_var) document.write(linebreak) my_var = "I am learning javascript!" document.write(my_var); document.write(linebreak) my_var = "Script is Finishing up..." document.write(my_var) </script> </body> 57
  • 58. 58
  • 59. We made two variables in this example. One to hold the HTML for a line break and the other was a dynamic variable that had a total of three different values throughout the script. To assign a value to a variable you use the equal sign (=) with the variable on the left and the value to be assigned on the right. If you swap the order then your script will not work correctly! In english the Javascript "myVar = 'Hello World!'" would be: myVar equals 'Hello World!'. The first time we used a variable we placed var in front to signify its first use. In subsequent assignments of the same variable we did not need the var. 59
  • 60. Javascript Variable Naming Conventions When choosing a variable name you must first be sure that you do not use any of the Javascript reserved names . Another good practice is choosing variable names that are descriptive of what the variable holds. If you have a variable that holds the size of a shoe, then name it "shoe_size" to make your Javascript more readable. 60
  • 61. Finally, Javascript variable names may not start with a numeral (0-9). These variable names would be illegal: 7lucky, 99bottlesofbeer, and 3zacharm. A good rule of thumb is to have your variable names start with a lowercase letter (a-z) and use underscores to separate a name with multiple words (i.e. my_var, strong_man, happy_coder, etc). 61
  • 62. Javascript Functions If you have any programming experience, then you do not need to spend much time on this . Functions in Javascript behave similar to numerous programming languages (C, C++, PHP, etc). If this is your first time learning about functions, then be sure to go through this very thoroughly as a solid understanding of functions will make the rest of this easier to follow 62
  • 63. What's a Function? A function is a piece of code that sits dormant until it is referenced or called upon to do its "function". In addition to controllable execution, functions are also a great time saver for doing repeatable tasks. Instead of having to type out the code every time you want something done, you can simply call the function multiple times to get the same effect. This benefit is also known as "code reusability” 63
  • 64. Example Function in Javascript A function does not execute when the page loads and so it should be placed inside the head of your HTML document. Creating a function is really quite easy, all you have to do is tell the browser you're making a function, give the function a name, and then write the Javascript like normal. 64
  • 65. HTML & JavaScript Code: <html> <head> <script type="text/javascript"> function popup() { document.write("Hello World!") } </script> </head> <body> <input type="button" onclick="popup()" value="popup"> </body> </html> 65
  • 66. We first told the browser we were going to be using a function by typing "function". Next, we gave our function a name, so that we could use it later. Since we are making a pop up , we called our function "popup". The curly braces "{,}" define the boundaries of our function code. All popup function code must be contained within the curly braces. 66
  • 67. What we didn't talk about was how we got this function to execute when the button is clicked. The click is called an event, and we will be talking about how to make functions execute from various types of events in the next lesson. 67
  • 68. Writing Your Own Function You can also make your own functions to be used on your webpage. If you would like to write your own function then you must use the special keyword function 68
  • 69. Events in Javascript The absolute coolest thing about Javascript is the ability to create dynamic web pages that increase user interaction, making the visitor feel like the website is almost coming alive right before their eyes. 69
  • 70. The building blocks of an interactive web page is the Javascript event system. An event in Javascript is something that happens with or on the web page. A few example of events: A mouse click The web page loading Mousing over a hot spot on the web page, also known as hovering Selecting an input box in an HTML form A keystroke 70
  • 71. A Couple of Examples Using Events Javascript has predefined names that cover numerous events that can occur, including the ones listed above. To capture an event and make something happen when that event occurs you must specify the event, the HTML element that will be waiting for the event, and the function(s) that will be run when the event occurs. 71
  • 72. <html> <head> <script type="text/javascript"> function popup() { document.write("hello") } </script> </head> <body> <input type="button" value="Click Me!" onclick="popup()"> <br /> <a href="#" onmouseover="popup()" > Hover Me!</a> </body> </html> 72
  • 73. 73
  • 74. 74
  • 75. <html> <head> <script type="text/javascript"> function popup() { document.write("hello") } </script> </head> <body> <input type="button" value="Click Me!" onclick="popup()"> <br /> <a href="#" onmouseout="popup()" > Hover Me!</a> </body> </html> 75
  • 76. 76
  • 77. 77
  • 78. With the button we used the event onClick event as our desired action and told it to call our popup function that is defined in our header. To call a function you must give the function name followed up with parenthesis "()". Our mouseover and mouseout events were combined on one HTML element, a link. We wanted to do nothing when someone put their mouse on the link, but when the mouse leaves (onMouseout) we displayed a popup. 78
  • 79. <html> <head> <script type="text/javascript"> function popup() { document.write("hello") } </script> </head> <body> <input type="button" value="Click Me!" onmouseout="popup()"> <br /> </body> </html> 79
  • 80. 80
  • 81. 81
  • 82. 82
  • 83. Javascript Statements All the Javascript code that you will write will, for the most part, be comprised of many separate statements. A statement is setting a variable equal to a value. A statement is also a function call, i.e. document.write(). Statements define what the script will do and how it will be done. 83
  • 84. Typical Ending of a Statement In typical programming languages like C , the end of a statement is marked with a semicolon(;), but we have seen that the colon is optional in javascript. In Javascript the end of a statement is most often marked by starting a new line. 84
  • 85. Categories of Statements In addition to the standard statements like changing a variable's value, assigning a new value, or calling a function, there are groups of statements that are distinct in their purpose. We will provide a brief overview of each of these categories . Conditional Statements Loop Statements Object Manipulation Statements Comment Statements Exception Handling Statements 85
  • 86. Conditional Statements If you were to win a 100 la Rs lottery then you would probably quit your job. That last statement is a conditional if/then statement that is used a great deal in programming. If some condition (winning the lottery) is true, then something happens (you quit your job). If the condition is false, then you probably will not take that action (quit your job). 86
  • 87. Conditional statements are used to control your scripts so that different actions can be taken depending on the situation. You may want to display a special image on your home page during the holidays. This condition would depend on what day it was, and if it was a holiday, then a special holiday image would be displayed to your visitors. Without proper knowledge of the conditional statement your scripts will not be as lively or dynamic as they could possibly be. 87
  • 88. Loop Statements Have you ever had to send out marriage announcements? If not, this is how it goes. You take the invitation, place it in the envelope, lick the envelope, seal the envelope, then send it off. Then you take the next invitation off the stack of 99 remaining invitations, place it in an envelope, lick the envelope, seal... You get the idea! It is a boring, repetitive task! Wouldn't it be great if there was an easier way? Well in programming and in Javascript there is. The process is called "looping" and it will turn your cute little scripts into massive work horses with the right planning 88
  • 89. A loop statement checks to see if some condition is true, say our condition is "Are there any invitations left?" and if that condition is true it will execute a chunk of code. Our code in this example would be to stuff, lick, and seal the envelope. After the code is executed the condition is checked again, if it is true then the process begins again, if it is false, then the loop code stops execution and the script continues along. Believe me when I say this is something you want to learn more about! 89
  • 90. Object Manipulation Statements These are statements that are used to take advantage of the object model to get tasks done. If you do not know about the object model at this time, do not worry. We will be talking about it later. 90
  • 91. Comment Statements Comment statements are used to prevent the browser from executing certain parts of code that you designate as non-code. Why would you want to do this? There are many reasons. By disallowing the block of text to be read you can then place in comments for yourself, much like HTML comments, and you can also block out segments of your code for whatever reason you may have. The single line comment is just two slashes (//) and the multiple line comment starts with (/*) and ends with (*/). 91
  • 92. Exception Handling Statements Sometimes when you are programming you do not know for sure if the file that you will be writing to, the input stream you are reading from, or the connection you have established will be usable for the code that you want to execute. There is a way to program safety mechanisms, so that your code handles common problems that may arise (maybe the input stream you are reading from suddenly disappears). The try...catch statement tries to execute a piece of code and if it fails the catch should handle the error gracefully. This is an advanced programming subject that is interesting, but not necessary for the majority of Javascript programmers. 92
  • 93. Javascript If Statement As your Javascript programs get more sophisticated you will need to make use of conditional statements that allow your program to make decisions. Nearly all other programming languages use conditionals and Javascript is no exception. 93
  • 94. The If Statement is a way to make decisions based on a variable or some other type of data. For example you might have a variable that stores the date. With this tiny bit of information you could easily program a small script to print out "Today is my Birthday!" whenever the day and month were equal to your birthday 94
  • 95. Javascript If Statement Syntax There are two major parts to an if statement: the conditional statement and the code to be executed. The conditional statement is a statement that will evaluate to either True or False. The most common type of a conditional statement used is checking to see if something equals a value. An example would be checking if the date equaled your birthday. 95
  • 96. The code to be executed contains the Javascript code that will be executed only if the If Statement's conditional statement was true. In this simple If Statement example we print out a message if the variable we are checking is equal to 7. 96
  • 97. <html> <body> <script type="text/javascript"> var myNum = 7 if(myNum == 7) { document.write("Lucky 7!") } </script> </body>html> 97
  • 98. 98
  • 99. This simple example created myNum and set it to 7. We then checked to see if myNum was equal to 7 "myNum == 7" in the If Statement's conditional statement which evaluated to True. Because the conditional statement was True the block of code associated with our If Statement "document.write..." was executed, as you can see in the Display. 99
  • 100. Javascript If Statement: Else We already taught you how to execute code if a given condition is True, but what if you want to execute another piece of code if something is False? The answer is to use an extension to the If Statement; the Else clause. The Else clause is executed when the conditional statement is False. Let's take our example from above, add an Else clause and change the value of myNum so that our conditional statement is False. 100
  • 101. <html> <script type="text/javascript"> var myNum = 10; if(myNum == 7){ document.write("Lucky 7!"); } else{ document.write("You're not very lucky today..."); } </script> </html> 101
  • 102. 102
  • 103. <html> <script type="text/javascript"> var visitor = "principal“ if(visitor == "teacher") { document.write("My dog ate my homework..."); } else if(visitor == "principal"){ document.write(“hello principal"); } else { document.write("How do you do?"); } </script></html> 103
  • 104. 104
  • 105. There are two important things to note about the Else If extension: You must have a normal If Statement before you can use the Else If statement. This is because the Else If statement is an addon to the If Statement. You can have multiple Else If add-ons. In our example we only used one Else If extension, but you can add as many as you require. 105
  • 106. Javascript While Loop The while loop is an advanced programming technique that allows you to do something over and over while a conditional statement is true. Although the general uses of the while loop are usually a bit complex, this lesson will teach you the basics of how to create a while loop in Javascript 106
  • 107. Javascript While Loop Explained There are two key parts to a Javascript while loop: The conditional statement which must be True for the while loop's code to be executed. The while loop's code that is contained in curly braces "{ and }" will be executed if the condition is True. When a while loop begins the Javascript interpreter checks the condition statement is true. If it is the code between the curly braces is executed. At the end of the code segment "}" the while loop loops back to the condition statement and begins again. If the condition statement is always True then you will never exit the while loop, so be very careful when using while loops 107
  • 108. Creating a Simple While Loop This example shows how to create a basic while loop that will execute a document.write 10 times and then exit the loop statement. 108
  • 109. <html> <script type="text/javascript"> var myCounter = 0; var linebreak = "<br />"; document.write("While loop is beginning"); document.write(linebreak); while(myCounter < 10){ document.write("myCounter = " + myCounter); document.write(linebreak); myCounter++; } document.write("While loop is finished!"); </script> </html> 109
  • 110. While loop is beginning myCounter = 0 myCounter = 1 myCounter = 2 myCounter = 3 myCounter = 4 myCounter = 5 myCounter = 6 myCounter = 7 myCounter = 8 myCounter = 9 While loop is finished! 110
  • 111. Our variable myCounter started off at 0, which is less than 10, so our while loop executed its code. The value 0 was printed to the browser and then myCounter was incremented by 1 and the while loop started over again. 1 was less than 10 so the while loop's code was executed...and the process repeats itself a few more times until... myCounter was 10 which was not less than 10 so the while loop's code did not execute. You can see this in the Display: because the last value to be printed out was 9. Note: Advanced programmers may recognize that a for loop would be a better solution for this example, but we hope you can ignore this for our needs to create an easy example! 111
  • 112. Javascript For Loop Explained There are four important aspects of a Javascript for loop: The counter variable is something that is created and usually used only in the for loop to count how many times the for loop has looped. The conditional statement that decides whether the for loop continues executing or not. This check usually includes the counter variable in some way. The counter variable is incremented after every loop in the increment section of the for loop. The code that is executed for each loop through the for loop. This may seem strange, but 1-3 all occur on the same line of code. This is because the for loop is such a standardized programming practice that the designers felt they might as well save some space and clutter when creating the for loop. 112
  • 113. <html> <script type="text/javascript"> var linebreak = "<br />“ document.write("For loop code is beginning") document.write(linebreak) for(i = 0; i < 5; i++) { document.write("Counter i = " + i) document.write(linebreak) } document.write("For loop code is finished!"); </script></html> 113
  • 114. For loop code is beginning Counter i = 0 Counter i = 1 Counter i = 2 Counter i = 3 Counter i = 4 For loop code is finished! 114
  • 115. The counter variable name i may seem a little strange, but it has been used for years now that you might as well get used to it as the default for loop counter. Other common variable names are j, k, x and y So in this example our counter was initially set to 0 with "i = 0;" and then the conditional statement "i < 5;" was executed. Our counter was indeed smaller than 5 and so the for loop's code was executed. After the loop's code had been executed then the increment "i++" happens, making the counter i equal to 1. The for loop then checked that i was less than 5, which it was, resulting in the loop's code being executed again. This looping happened a couple more times until i was equal to 5, which is not less than 5 and the for loop stopped executing. For loops may seem very confusing at first, but let me assure you, they are quite useful and should be studied thoroughly by anyone who wishes to become a intermediate programmer. 115
  • 116. Javascript Comments Have you ever written a script or a program in the past only to look at it 6 months later and have no idea what's going on in the code? You probably forgot to do what all programmers tend to forget: write comments! 116
  • 117. When writing code you may have some complex logic that is confusing, this is a perfect opportunity to include some comments in the code that will explain what is going on. Not only will this help you remember it later on, but if you someone else views your code they will also be able to understand the code (hopefully)! Another great thing about comments is the ability for comments to remove bits of code from execution when you are debugging your scripts. This lesson will teach you how to create two types of comments in Javascript: single line comments and multi-line comments. 117
  • 118. Creating Single Line Comments To create a single line comment in Javascript you place two slashes "//" in front of the code or text you wish to have the Javascript interpreter ignore. When you place these two slashes, all text to the right will be ignored, until the next line. These types of comments are create for commenting out single lines of code and writing small notes. 118
  • 119. <html> <script type="text/javascript"> // This is a single line Javascript comment document.write("I have comments in my Javascript code!") //document.write("You can't see this!"); </script> <html> 119
  • 120. I have comments in my Javascript code! 120
  • 121. Creating Multi-line Comments Although a single line comment is quite useful, it can sometimes be burdensome to use for large segments of code you wish to disable or extra long winded comments you need to insert. For this large comments you can use Javascript's multi-line comment that begins with /* and ends with */. 121
  • 122. <html> <script type="text/javascript"> document.write("I have multi-line comments!"); /*document.write("You can't see this!"); document.write("You can't see this!"); document.write("You can't see this!"); document.write("You can't see this!"); document.write("You can't see this!"); document.write("You can't see this!"); document.write("You can't see this!");*/ </script> </html> 122
  • 123. I have multi-line comments! Quite often text editors have the ability to comment out many lines of code with a simple key stroke or option in the menu. If you are using a specialized text editor for programming be sure that you check and see if it has an option to easily comment out many lines of code! 123
  • 124. Javascript Array An array is a variable that can store many variables. Many programmers have seen arrays in other languages and they aren't that different in Javascript 124
  • 125. The following points should always be remembered when using arrays in Javascript: The array is a special type of variable. Values are stored into an array by using the array name and by stating the location in the array you wish to store the value in brackets. Example: myArray[2] = "Hello World"; Values in an array are accessed with the array name and location of the value. Example: myArray[2]; Javascript has built in functions for arrays, so check out these built in array functions before writing code yourself! 125
  • 126. Creating a Javascript Array Creating an array is slightly different than creating a normal variable. Because Javascript has variables and properties associated with arrays, you have to use a special function to create a new array. This example shows how you would create a simple array, store values to it and access these values. 126
  • 127. <html> <script type="text/javascript"> var myArray = new Array() myArray[0] = "Baseball” myArray[1] = "Cricket" myArray[2] = "Football" document.write(myArray[0] + myArray[1] + myArray[2]); </script></html> 127
  • 128. 128
  • 129. Display: FootballBaseballCricket Notice that you set values and get values from an array by specifying the position, in brackets, of the value you want to use. 129
  • 130. Javascript Array Sorting Imagine that you wanted to sort an array alphabetically before you wrote the array to the browser. Well, this code has already been written and can be accessed by using the Array'ssort method. 130
  • 131. <html> <script type="text/javascript"> var myArray = new Array() myArray[0] = “q“ myArray[1] = “w“ myArray[2] = “e“ myArray.sort() document.write(myArray[0] + myArray[1] + myArray[2]); </script><html> 131
  • 132. 132
  • 133. Javascript Alert - What is it? If you do not have Javascript enabled on your web browser, then you may have been able to avoid them in your internet history. The Javascript alert is a dialogue box that pops up and takes the focus away from the current window and forces the web browser to read the message 133
  • 134. You may have noticed that you didn't get a Javascript alert popup when you came to this page. That is because doing so would be in bad taste for a web designer. You see, alerts should be very, very rarely used and even then these following guidelines should be considered when using them. 134
  • 135. When to Use Popups / Alerts Javascript alerts are ideal for the following situations: If you want to be absolutely sure they see a message before doing anything on the website. You would like to warn the user about something. For example "the following page contains humor not suitable for those under the age of 14." An error has occurred and you want to inform the user of the problem. When asking the user for confirmation of some action. For example they have just agreed to sign over the deed to their house and you want to ask them again if they are absolutely positive they want to go through with this decision! Even though the above situations would all be valid times to use the alert function, you could also skip the alert and just have the error message, confirmation, etc displayed in plain HTML, instead of in a popup. More and more bigger sites are opting to lose the Javascript alerts and instead keep everything in HTML. 135
  • 136. Coding a Simple Javascript Alert Just for fun, let us suppose that we are making an alert for some website that asks people to hand over the deed to their house. We need to add an alert to be sure these people are in agreement. The following code will add an alert by using an HTML button and the onClick event. 136
  • 137. <html> <form> <input type="button" onclick= "alert('Are you sure you want to give us the deed to your house?')" value="Confirmation Alert"> </form> </html> 137
  • 138. 138
  • 139. 139
  • 140. Javascript Confirm The Javascript confirm function is very similar to the Javascript alert function. A small dialogue box pops up and appears in front of the web page currently in focus. The confirm box is different than the alert box in that it supplies the user with a choice, they can either press OK to confirm the popups message or they can press cancel and not agree to the popups request. 140
  • 141. Confirmation are most often used to confirm an important action that is taking place on a website. For example they may be about to submit an order or about to visit a link that will take them away from the current website. 141
  • 143. <html> <head> <script type="text/javascript"> function confirmation() { var answer = confirm(“hello atul") if (answer) { alert("Bye bye!") window.location = “tt.html“ } else { alert("Thanks for sticking around!") } } </script> </head> <body> <form> <input type="button" onclick="confirmation()" value="Leave atul.com"> </form> </body> </html> 143
  • 144. 144
  • 145. 145
  • 146. 146
  • 147. 147
  • 148. 148
  • 149. 149
  • 150. Confirm returns the value 1 if the user clicks OK and the value 0 if the user clicks Cancel. We store this value in answer by setting it equal to the confirm function call. After answer has stored the value, we then use answer as a conditional statement. If answer is anything but zero, then we are going to send the user away from tt.html . If answer is equal to zero, then we will keep the user at ttt.html because they clicked the Cancel button. In either case we have a Javascript alert box that appears to inform the user what is going to happen. "Bye bye!" if they chose to leave and "Thanks for sticking around!" if they chose to stay 150
  • 151. In this lesson we also used the window.location property for the first time. Whatever we set window.location to will be where the browser is redirected to.We will also discuss redirection later on. 151
  • 152. Javascript Prompt The Javascript prompt is a relic from the 1990's that you seldom see being used in modern day websites. The point of the Javascript prompt is to gather information from the user so that it can be used throughout the site to "personalize" it for the visitor. 152
  • 153. Back in the day you'd often see these prompts on personal web pages asking for your name. After you typed in the information you would be greeted with a page that had a welcome message, such as "Welcome to My Personal Web Page ATUL Kahate!" (If you name just happened to be ATUL Kahate). The Javascript prompt is not very useful and many find it slightly annoying, but hey, this lesson is here to educate you, so let's learn how to make that prompt! 153
  • 154. Simple Javascript Prompt You can use a prompt for a wide variety of useless tasks, but below we use it for an exceptionally silly task. Our prompt is used to gather the user's name to be displayed in our alert dialogue box. 154
  • 155. <html> <head> <script type="text/javascript"> function prompter() { var reply = prompt("Hey there, good looking stranger! What's your name?", "") alert (reply) } </script> </head> <body> <input type="button" onclick="prompter()" value="Say my name!"> </body> 155
  • 156. 156
  • 157. 157
  • 158. 158
  • 159. Recap on Javascript Prompt It sure is a quick way to gather some information, but it is not as a reliable information gatherer as the other options available to you. If you want to find out someone's name and information, the best way to request this information would be to use HTML Forms. 159
  • 160. Javascript Print Function The Javascript print function performs the same operation as the print option that you see at the top of your browser window or in your browser's "File" menu. The Javascript print function will send the contents of the webpage to the user's printer. 160
  • 161. Many believe this function to be worthless, but there are many computer users that do not know their way around a computer all that well and it can sometimes create a more user friendly experience when you provide as many helpful features as possible 161
  • 162. Javascript Print Script - window.print() The Javascript print function window.print() will print the current web page when executed. In this example script we will be placing the function on a Javascript button that will perform the print operation when the onClick event occurs. 162
  • 163. HTML & Javascript Code: <HTML> <form> <input type="button" value="Print This Page" onClick="window.print()" /> </form> </HTML> 163
  • 164. 164
  • 165. 165
  • 166. JavaScript Redirect You're moving to a new domain name. You have a time-delay in place on your download site. You have a list of external web servers that are helping to mirror your site. What will help you deal and/or take advantage of these situations? Javascript redirects will. 166
  • 167. When a web page is moved will most probably would like to place a "redirect" page at the old location that informs the visitor of the change and then after a timed delay, will forward the visitor to the new location. With the javascript redirection, you can do just this. 167
  • 168. Javascript Window.Location The control over what page is loaded into the browser rests in the javascript propety window.location, by setting this equal to a new URL you will in turn change from the current web page to the one that is specified. If you wanted to redirect all your visitors to www.google.com when they arrived at your site you would just need the script below: 168
  • 169. HTML & Javascript Code: <script type="text/javascript"> window.location = "http://www.google.com/" </script> 169
  • 170. Javascript Time Delay Implementing a timed delay in javascript is useful for the following situations: Showing an "Update your bookmark" page when you have to change URLs or page locations For download sites that wish to have a few second delay before the page loads and when the download starts To refresh a web page every specified amount of seconds The code for this timed delay is slightly involved and is beyond the scope of this tutorial. However, we have tested it and it seems to function properly. 170
  • 171. Redirect a web page There are a couple of ways to redirect to another webpage with JavaScript. The most popular ones are location.href and location.replace: window.location.href = "http://www.w3schools.com"; // Simulate an HTTP redirect: window.location.replace("http://www.w3schools.com"); The difference between href and replace, is that replace() removes the URL of the current document from the document history, meaning that it is not possible to use the "back" button to navigate back to the original document.
  • 172. <html> <head> <script type="text/javascript"> function delayer() { window.location = “tt.html" } </script> </head> <body onLoad="setTimeout('delayer()', 5000)"> <h2 >Prepare to be redirected!</h2> <p>This page is a time delay redirect, please update your bookmarks to our new location!</p> </body> </html> 172
  • 173. 173
  • 174. 174
  • 175. The most important part of getting the delay to work is being sure to use the javascript function setTimeout. We want the delayer() function be used after 5 seconds or 5000 miliseconds, so we pass the setTimeout() two arguments. 'delayer()' - The function we want setTimeout() to execute after the specified delay. 5000 - the number of milisecods we want setTimeout() to wait before executing our function. 1000 miliseconds = 1 second. 175
  • 176. Web Page Redirection Do use javascript for redirections when you change your website's URL or move a file to a new location. Don't use redirections when they could easily be replaced with a normal HTML hyperlink. 176
  • 177. Javascript Popups Chances are if you are reading this web page then you have experienced hundreds of Javascript popup windows throughout your web surfing lifetime. Want to dish out some pain of your own creation onto unsuspecting visitors? I hope not! Because web sites with irrelevant popups are bad! 177
  • 178. However, we will show you how to make windows popup for reasonable occasions, like when you want to display extra information, or when you want to have something open a new window that isn't an HTML anchor tag <a>. 178
  • 179. Javascript window.open Function The window.open() function creates a new browser window, customized to your specifications, without the use of an HTML anchor tag. In this example we will be making a function that utilizes the window.open() function. 179
  • 180. <head> <script type="text/javascript"> function myPopup() { window.open( “tt.html" ) } </script> </head> <body> <form> <input type="button" onClick="myPopup()" value="POP!"> </form> <p onClick="myPopup()">CLICK ME TOO!</p> </body> 180
  • 181. 181
  • 182. 182
  • 183. This works with pretty much any tag that can be clicked on, so please go ahead an experiment with this fun little tool. 183
  • 184. Javascript Window.Open Arguments There are three arguments that the window.open function takes. First the relative or absolute URL of the web page to be opened. Secondly, a text name for the window, and lastly a long string that contains all the different properties of the window. 184
  • 185. dependent - Subwindow closes if parent(the window that opened it) window closes fullscreen - Display browser in full screen mode height - The height of the new window, in pixels width - The width of the new window, in pixels left - Pixel offset from the left side of the screen top - Pixel offset from the top of the screen resizable - Allow the user to resize the window or prevent resizing status - Display the status bar or not 185
  • 186. Dependent, fullscreen, resizable, and status are all examples of ON/OFF properties. You can either set them equal to zero to turn them off, or set them to one to turn them ON. There is no inbetween setting for these types of properties 186
  • 187. Upgraded Javascript Popup Window! Now that we have the tools, let's make a sophisticated Javascript popup window that we can be proud of. 187
  • 188. <head> <script type="text/javascript"> function myPopup2() { window.open( “tt.html", "myWindow", "status = 0, height = 300, width = 300, resizable = 0" ) } </script> </head> <body> <form> <input type="button" onClick="myPopup2()" value="POP2!"> </form> <p onClick="myPopup2()">CLICK ME TOO!</p> </body> 188
  • 189. 189
  • 190. 190
  • 191. <head> <script type="text/javascript"> function myPopup2() { window.open( “tt.html", "myWindow", "status = 1, height = 300, width = 300, resizable = 0" ) } </script> </head> <body> <form> <input type="button" onClick="myPopup2()" value="POP2!"> </form> <p onClick="myPopup2()">CLICK ME TOO!</p> </body> 191
  • 192. 192
  • 193. Now that is a prime example of a worthless popup! When you make your own, try to have them relate to your content, like a small popup that has no navigation that just gives the definition or explanation of a word, sentence, or picture! 193
  • 194. Javascript Date and Time Object The Date object is useful when you want to display a date or use a timestamp in some sort of calculation. In java you can either make a Date object by supplying the date of your choice, or you can let Javascript create a Date object based on your visitor's system clock. It is usually best to let Javascript simply use the system clock. 194
  • 195. When creating a Date object based on the computer's (not web server's!) internal clock, it is important to note that if someone's clock is off by a few hours or they are in a different time zone, then the Date object will create a different time than the one created with your own computer. 195
  • 196. Javascript Date Today (Current) To warm up our Javascript Date object skills, let's do something easy. If you do not supply any arguments to the Date constructor (this makes the Date object) then it will create a Date object based on the visitor's internal clock. 196
  • 197. <html> <h4>It is now <script type="text/javascript"> var currentTime = new Date() document.write(currentTime ) </script> </h4> </html> 197
  • 198. 198
  • 199. Nothing shows up! That's because we still don't know the methods of the Date object that let us get the information we need(i.e. Day, Month, Hour, etc). 199
  • 200. Get the Javascript Time The Date object has been created and now we have a variable that holds the current date. To get the information we need to print out the date we have to utilize some or all of the following functions 200
  • 201. getTime() - Number of milliseconds since 1/1/1970 @ 12:00 AM getSeconds() - Number of seconds (0-59) getMinutes() - Number of minutes (0-59) getHours() - Number of hours (0-23) getDay() - Day of the week(0-6). 0 = Sunday, ... , 6 = Saturday getDate() - Day of the month (1-31) getMonth() - Number of month (0-11) getFullYear() - The four digit year (1970-9999) 201
  • 202. <html> <h4>It is now <script type="text/javascript"> var currentTime = new Date() var month = currentTime.getMonth() var day = currentTime.getDate() var year = currentTime.getFullYear() document.write(month + "/" + day + "/" + year) </script> </h4> </html> 202
  • 203. 203
  • 204. Javascript Current Time Clock Now instead of displaying the date we will display the format you might see on a typical digital clock HH:MM AM/PM (H = Hour, M = Minute). 204
  • 205. <html> <h4>It is now <script type="text/javascript"> var currentTime = new Date() var hours = currentTime.getHours() var minutes = currentTime.getMinutes() if (minutes < 10) minutes = "0" + minutes document.write(hours + ":" + minutes + " ") if(hours > 11) { document.write("PM") } else { document.write("AM") } </script> </h4> 205
  • 206. 206
  • 207. We check to see if hours or minutes is less than 10, if it is then we need to add a zero to the beginning of minutes. This is not necessary, but if it is 1:01 AM then our clock would output "1:1 AM", which doesn't look very nice at all! 207
  • 208. Javascript Form Validation There's nothing more troublesome than receiving orders, guestbook entries, or other form submitted data that are incomplete in some way. You can avoid these headaches once and for all with Javascript's amazing way to combat bad form data with a technique called "form validation". 208
  • 209. The idea behind Javascript form validation is to provide a method to check the user entered information before they can even submit it. Javascript also lets you display helpful alerts to inform the user what information they have entered incorrectly and how they can fix it. In this lesson we will be reviewing some basic form validation, showing you how to check for the following: 209
  • 210. If a text input is empty or not If a text input is all numbers If a text input is all letters If a text input is all alphanumeric characters (numbers & letters) If a text input has the correct number of characters in it (useful when restricting the length of a username and/or password) If a selection has been made from an HTML select input (the drop down selector) If an email address is valid How to check all above when the user has completed filling out the form 210
  • 211. Form Validation - Checking for Non-Empty This has to be the most common type of form validation. You want to be sure that your visitors enter data into the HTML fields you have "required" for a valid submission. Below is the Javascript code to perform this basic check to see if a given HTML input is empty or not. 211
  • 212. <html> <head> <script type='text/javascript'> function check(form) { var valu=form.fname.value if(valu==“”) alert(“plz enter something”) else document.write(valu) } </script> </head> <form> Required Field: <input type='text' name=“fname"> <input type='button' onclick=check(this.form) value='Check Field' /> </form> 212
  • 213.
  • 214.
  • 215. 215
  • 216. 216
  • 218. <html> <head><script type="text/javascript"> function notEmpty() { var myTextField =document.getElementById('myText'); if(myTextField.value != "") alert("You entered: " + myTextField.value) else alert("Would you please enter some text?") } </script></head> <input type='text' id='myText' > <input type='button' onclick='notEmpty()' value='Form Checker' /> </html> 218
  • 219. 219
  • 220. 220
  • 221. 221
  • 222. Form Validation - Checking for Non- Empty 222
  • 223. <html><head> <script type='text/javascript'> function isEmpty(elem, helperMsg) { if(elem.value.length == 0) { alert(helperMsg); return true; } return false; } </script></head> <form> Required Field: <input type='text' id='req1'/> <input type='button' onclick="isEmpty(document.getElementById('req1’), 'Please Enter a Value')" value='Check Field' /> </form> 223
  • 224. 224
  • 225. 225
  • 226. 226
  • 227. <html><head> <script type='text/javascript'> function isEmpty(elem, helperMsg) { if(elem.value.length == 0) { alert(helperMsg); elem.focus(); return true; } return false; } </script></head> <form> Required Field: <input type='text' id='req1'/> <input type='button' onclick="isEmpty(document.getElementById('req1’), 'Please Enter a Value')" value='Check Field' /> </form> 227
  • 228. 228
  • 229. 229
  • 230. 230
  • 231. The function isEmpty will check to see that the HTML input that we send it has something in it. elem is a HTML text input that we send this function. Javascriptstrings have built in properties, one of which is the length property which returns the length of the string. The chunk of code elem.value will grab the string inside the input and by adding on length elem.value.length we can see how long the string is. 231
  • 232. As long as elem.value.length isn't 0 then it's not empty and we return true, otherwise we send an alert to the user with a helperMsg to inform them of their error and return false 232
  • 233. Form Validation - Checking for All Numbers 233
  • 234. Regular Expression(RegExp) Character Meaning / backslash is an escape character in string literals. Ex: /[a-z]s/I : an expression that searches for any letter in the range A-Z followed by a whitespace character ^ Matches beginning of input Ex: , /^A/ does not match the 'A' in "an A", but does match the 'A' in "An E". $ Matches end of input. For example, /t$/ does not match the 't' in "eater", but does match it in "eat". * Matches the preceding expression 0 or more times. Equivalent to {0,}. For example, /bo*/ matches 'boooo' in "A ghost booooed" and 'b' in "A bird warbled" but nothing in "A goat grunted". + Matches the preceding expression 1 or more times. Equivalent to {1,}. For example, /a+/ matches the 'a' in "candy" and all the a's in "caaaaaaandy", but nothing in "cndy". ? Matches the preceding expression 0 or 1 time. Equivalent to {0,1}.
  • 235. (x) Matches 'x' and remembers the match, as the following example shows. The parentheses are called capturing parentheses. The '(foo)' and '(bar)' in the pattern /(foo) (bar) 1 2/ match and remember the first two words in the string "foo bar foo bar". (?:x) Matches 'x' but does not remember the match. (?<=y)x Matches 'x' only if 'x' is followed by 'y'. This is called a lookahead. x(?!y) Matches 'x' only if 'x' is not followed by 'y'. This is called a negated lookahead (?<=y)x Matches x only if x is preceded by y. This is called a lookbehind. x|y Matches 'x', or 'y' (if there is no match for 'x'). {n} Matches exactly n occurrences of the preceding expression. N must be a positive integer. {n,} Matches at least n occurrences of the preceding expression. N must be a positive integer. {n,m} Where n and m are positive integers and n <= m. Matches at least n and at most m occurrences of the preceding expression. When m is omitted, it's treated as ∞. [xyz] Character set. This pattern type matches any one of the characters in the brackets, including escape sequences.
  • 236. Sr.No . Expression & Description 1 [...] Any one character between the brackets. 2 [^...] Any one character not between the brackets. 3 [0-9] It matches any decimal digit from 0 through 9. 4 [a-z] It matches any character from lowercase a through lowercase z. 5 [A-Z] It matches any character from uppercase A through uppercase Z. 6 [a-Z]
  • 237. <html><head> <script type='text/javascript'> function isNumeric(elem, helperMsg){ var numericExpression = /^[0-9]+$/; if(elem.value.match(numericExpression)) { return true; } else{ alert(helperMsg); elem.focus(); return false; } } </script></head> <form> Numbers Only: <input type='text' id='numbers'/> <input type='button' onclick="isNumeric(document.getElementById('numbers'), 'Numbers Only Please')" value='Check Field' /> </form></html> 237
  • 238. 238
  • 239. Form Validation - Checking for All Letters 239
  • 240. <html><head> <script type='text/javascript'> function isAlphabet(elem, helperMsg) { var alphaExp = /^[a-zA-Z]+$/; if(elem.value.match(alphaExp)) { return true; } else{ alert(helperMsg); elem.focus(); return false; } } </script><head> <form> Letters Only: <input type='text' id='letters'/> <input type='button' onclick="isAlphabet(document.getElementById('letters'), 'Letters Only Please')" value='Check Field' /> </form> </html> 240
  • 241. 241
  • 242. Form Validation - Checking for Numbers and Letters 242
  • 243. <html><head> <script type='text/javascript'> function isAlphabet(elem, helperMsg) { var alphaExp = /^[0-9a-zA-Z]+$/; if(elem.value.match(alphaExp)) { return true; } else{ alert(helperMsg); elem.focus(); return false; } } </script><head> <form> Letters Only: <input type='text' id='letters'/> <input type='button' onclick="isAlphabet(document.getElementById('letters'), 'Letters Only Please')" value='Check Field' /> </form> </html> 243
  • 244. 244
  • 245. Form Validation - Restricting the Length 245
  • 246. <html<<head> <script type='text/javascript'> function lengthRestriction(elem, min, max) { var uInput = elem.value; if(uInput.length >= min && uInput.length <= max) { return true; } else{ alert("Please enter between " +min+ " and " +max+ " characters"); elem.focus(); return false; } } </script></head> <form> Username(6-8 characters): <input type='text' id='restrict'/> <input type='button' onclick="lengthRestriction(document.getElementById('restric t'), 6, 8)" value='Check Field' /> </form> </html> 246
  • 247. 247
  • 248. 248
  • 249. 249
  • 250. Form Validation - Selection Made 250
  • 251. Form Validation - Selection Made To be sure that someone has actually selected a choice from an HTML select input you can use a simple trick of making the first option as helpful prompt to the user and a red flag to you for your validation code. By making the first option of your select input something like "Please Choose" you can spur the user to both make a selection and allow you to check to see if the default option "Please Choose" is still selected when the submit the form. 251
  • 252. function madeSelection(elem, helperMsg) { if(elem.value == "Please Choose") { alert(helperMsg); elem.focus(); return false; } else { return true; } } 252
  • 253. <html><head> <script type='text/javascript'> function madeSelection(elem, helperMsg) { if(elem.value == "Please Choose") { alert(helperMsg); elem.focus(); return false; } else{ return true; } } </script><head> <form> Selection: <select id='selection'> <option>Please Choose</option> <option>CA</option> <option>WI</option> <option>XX</option> </select> <input type='button' onclick="madeSelection(document.getElementById('selection' ), 'Please Choose Something')" value='Check Field' /> </form> </html> 253
  • 255. <script type='text/javascript'> function emailValidator(elem, helperMsg){ var emailExp = /^[w-.+]+@[a-zA-Z0-9.-]+.[a- zA-z0-9]{2,4}$/; if(elem.value.match(emailExp)){ return true; }else{ alert(helperMsg); elem.focus(); return false; } } </script> <form> Email: <input type='text' id='emailer'/> <input type='button' onclick="emailValidator1(document.getElementBy Id('emailer'), 'Not a Valid Email')" value='Check Field' /> </form> 255
  • 256. <html> <head> <script> function validateForm() { var x = document.forms["myForm"]["email"].value; var atpos = x.indexOf("@"); var dotpos = x.lastIndexOf("."); if (atpos<1 || dotpos<atpos+2 || dotpos+2>=x.length) { alert("Not a valid e-mail address"); return false; } } </script> </head> <body> <form name="myForm" action="/action_page.php" onsubmit="return validateForm();" method="post"> Email: <input type="text" name="email"> <input type="submit" value="Submit"> </form> </body> </html>
  • 258. <html> <head> <script type="text/javascript"> function show_coords(event) { x=event.clientX y=event.clientY alert("X coords: " + x + ", Y coords: " + y) }</script></head> <body onmousedown="show_coords(event)"> <p>Click in the document. An alert box will alert the x and y coordinates of the mouse pointer.</p></body></html> 258
  • 259. 259
  • 260. <html> <head> <script type="text/javascript"> function whichButton(event) { alert(event.keyCode) } </script></head> <body onkeyup="whichButton(event)"> <p><b>Note:</b> Make sure the right frame has focus when trying this example!</p> <p>Press a key on your keyboard. An alert box will alert the unicode of the key pressed.</p> </body> </html> 260
  • 261. 261
  • 262. <html> <head> <script type="text/javascript"> function isKeyPressed(event) { if (event.shiftKey==1) { alert("The shift key was pressed!")} else { alert("The shift key was NOT pressed!") }}</script></head> <body onmousedown="isKeyPressed(event)"> <p>Click somewhere in the document. An alert box will tell you if you pressed the shift key or not.</p> </body></html> 262
  • 263. 263
  • 264. <html><head> <script type="text/javascript"> function getEventType(event) { alert(event.type); } </script></head> <body onmousedown="getEventType(event)"> <p>Click in the document. An alert box will tell what type of event that was triggered.</p> </body> </html> 264
  • 265. 265
  • 269. 269
  • 270. Simple Javscript Void 0 Simple Example 270
  • 271. <html> <a href="javascript: void(0)">I am a useless link</a> </html> 271
  • 272. 272
  • 273. Simple Javscript Void 0 Useful Example 273
  • 275. 275
  • 279. <html> <body> <script type="text/javascript"> var txt="Hello World!" document.write(txt.length) </script> </body> </html> 279
  • 280. 12 280
  • 281. <html><body><script type="text/javascript"> var txt="Hello World!" document.write("<p>Big: " + txt.big() + "</p>") document.write("<p>Small: " + txt.small() + "</p>") document.write("<p>Bold: " + txt.bold() + "</p>") document.write("<p>Italic: " + txt.italics() + "</p>") document.write("<p>Blink: " + txt.blink() + " (does not work in IE)</p>") document.write("<p>Fixed: " + txt.fixed() + "</p>") document.write("<p>Strike: " + txt.strike() + "</p>") document.write("<p>Fontcolor: " + txt.fontcolor("Red") + "</p>") document.write("<p>Fontsize: " + txt.fontsize(16) + "</p>") document.write("<p>Lowercase: " + txt.toLowerCase() + "</p>") document.write("<p>Uppercase: " + txt.toUpperCase() + "</p>") document.write("<p>Subscript: " + txt.sub() + "</p>") document.write("<p>Superscript: " + txt.sup() + "</p>") document.write("<p>Link: " + txt.link("http://www.w3schools.com") + "</p>") </script></body></html> 281
  • 282. 282
  • 284. <html> <body> <script type="text/javascript"> var str="Hello world!" document.write(str.indexOf("Hello") + "<br />") document.write(str.indexOf("World") + "<br />") document.write(str.indexOf("world")) </script> </body> </html> 284
  • 285. 285
  • 287. <html> <body> <script type="text/javascript"> var str="Visit Microsoft!" document.write(str.replace(/Microsoft/,“IMS" )) </script> </body> </html> 287
  • 288. 288
  • 290. <html> <body> <script type="text/javascript"> document.write(Math.round(0.60) + "<br />") document.write(Math.round(0.50) + "<br />") document.write(Math.round(0.49) + "<br />") document.write(Math.round(-4.40) + "<br />") document.write(Math.round(-4.60)) </script> 290
  • 291. 291
  • 293. 293
  • 294. <html> <body> <script type="text/javascript"> document.write(Math.max(5,7) + "<br />") document.write(Math.max(-3,5) + "<br />") document.write(Math.max(-3,-5) + "<br />") document.write(Math.max(7.25,7.30)) </script></body> </html> 294
  • 295. 295
  • 296. <html> <body> <script type="text/javascript"> document.write(Math.min(5,7) + "<br />") document.write(Math.min(-3,5) + "<br />") document.write(Math.min(-3,-5) + "<br />") document.write(Math.min(7.25,7.30)) </script></body> </html> 296
  • 297. 297
  • 298. <html> <body> <script type="text/javascript"> document.write(Math.abs(7.25) + "<br />") document.write(Math.abs(-7.25)) </script> 298
  • 299. 299
  • 302. 302
  • 303. <html> <head> <script type="text/javascript"> function closeWin() { myWindow.close()} </script></head><body> <script type="text/javascript"> myWindow=window.open('','','width=200,height=100') myWindow.document.write("This is 'myWindow'") </script> <input type="button" value="Close 'myWindow'" onclick="closeWin()" /> </body> </html> 303
  • 304. 304
  • 305. <html> <head> <script type="text/javascript"> function goBack() { window.history.back() } </script> </head> <body><input type="button" value="Back" onclick="goBack()" /></body> </html> 305
  • 306. 306
  • 307. The go() method loads a specific page in the history list. Syntax history.go(number|URL) 307
  • 308. <html> <head> <script type="text/javascript"> function goBack() { window.history.go(-1) } </script> </head> <body> <input type="button" value="Back" onclick="goBack()" > </body> </html> 308
  • 310. <HTML> <HEAD> <TITLE>JavaScript Example</TITLE> </HEAD><BODY> <CENTER> <FORM><INPUT TYPE="button" VALUE="silver" ONCLICK="document.bgColor='silver'"> <INPUT TYPE="button" VALUE="slate" ONCLICK="document.bgColor='lightslategray'"> <INPUT TYPE="button" VALUE="green" ONCLICK="document.bgColor='lightgreen'"> <INPUT TYPE="button" VALUE="blue" ONCLICK="document.bgColor='lightblue'"> <INPUT TYPE="button" VALUE="white" ONCLICK="document.bgColor='white'"> </FORM></BODY></HTML> 310
  • 311. 311
  • 312. 312
  • 313. 313
  • 315. <html><head> <script type="text/javascript" language="JavaScript"> function handler(c){ c.checked = true; return 0 } </script></head> <form name="formA" action="javascript:void(0)"> <textarea rows="10" cols="45" onclick="handler(formA.click)" onmouseover="handler(formA.over)"></textarea> <br><br> Click<input type="checkbox" name="click">&nbsp; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;MouseOver<input type="checkbox" name="over"> </form></html> 315
  • 316. 316
  • 318. <html><head> <script type="text/javascript" language="JavaScript"> function handler(c,t,s) { t.value=s c.checked = true; return 0 }</script></head> <form name="formA" action="javascript:void(0)"> <textarea rows="10" cols="45" onclick="handler(formA.click,formB.t1,'click')" onmouseover="handler(formA.over,formB.t1,'mouseover')"></textarea><b r><br> Click<input type="checkbox" name="click">&nbsp; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;MouseOver<input type="checkbox" name="over"> </form> <form name="formB"> <textarea name="t1" rows="8" cols="45" wrap='soft'></textarea> </html> 318
  • 319. 319
  • 321. <htrml><head> <script type="text/javascript" language="JavaScript"> function handler(t,c,s) { t.value += s; c.checked = true; return 0 } </script> </head> <form name="formA" action="javascript:void(0)" onreset= "handler(formB.t1, formB.reset, 'reset ')" onsubmit="handler(formB.t1, formB.submit, 'submit ')"> <textarea rows="4" cols="45" wrap="soft" 321
  • 322. ondblclick= "handler(formB.t1, formB.dblclick, 'dblclick ')" onmouseover="handler(formB.t1, formB.over, 'over ')" onmouseout= "handler(formB.t1, formB.out, 'out ')" > Move the mouse, click and type here. Try selecting text. </textarea> <input type="Reset"> <input type="Submit" value="Submit"> </form> <form name="formB"> <textarea name="t1" rows="8" cols="45" wrap="soft"></textarea> click:<input type="checkbox" name="click"> </form> 322
  • 323. 323
  • 325. <html><head> <script type="text/javascript"> txtsize=0 maxsize=100 function writemsg() {if (txtsize<maxsize) { document.getElementById('msg').style.fontSize=txtsize txtsize++ timer=setTimeout("writemsg()",10) }} function stoptimer() {clearTimeout(timer)} 325
  • 326. 326
  • 328. <html><head><script type="text/javascript"> function newColor(color) {document.getElementById('x').style.background=color} </script></head><body> <p>This example demonstrates how to change the background color of a textarea.</p> <p>Mouse over the three colored table cells, and the textarea will change color:</p> <table width="100%"><tr> <td bgcolor="red" onmouseover="newColor('red')">&nbsp;</td> <td bgcolor="blue" onmouseover="newColor('blue')">&nbsp;</td> <td bgcolor="green" 328
  • 329. 329
  • 330. <html><head> <script language=javascript type="text/javascript"> x = "This text will scroll to the left slowly! ... " x = x + x i = 0 function scroll(){ window.defaultStatus=x.substring(i,x.length) + x i++ if (i==x.length) i=0 ; tid=setTimeout("scroll()", 100) } y=" " function stopScroll(){ window.defaultStatus=" " window.clearTimeout(tid); 330
  • 331. 331
  • 332. <html><head><script language=javascript type="text/javascript"> var plus,minus,divide,times function initialise(){ plus=document.calc.operator.options[0] minus=document.calc.operator.options[1] divide=document.calc.operator.options[2] times=document.calc.operator.options[3]} function calculate(){ x = parseInt(document.calc.val1.value) y = parseInt(document.calc.val2.value) if (plus.selected) document.calc.answer.value=x + y if (minus.selected) document.calc.answer.value=x - y 332
  • 333. <body onLoad="initialise()"> <h2>Calculator</h2> <form name="calc" action="post"> <input type=text name=val1 size=10> <select name=operator><option value=plus>+ <option value=minus>-<option value=divide>/ <option value=times>*</select> <input type=text name=val2 size=10>= <input type=text name=answer size=10> <input type=button value=answer onClick="calculate()"> </form</body></html> 333
  • 334. 334
  • 335. Changing Text with innerHTML 335
  • 336. <html><head> <script type="text/javascript"> function changeText() { document.getElementById('boldStuff').innerHTML = ‘ATUL KAHATE'; } </script></head> <body> <form> <p>Welcome to the site <b id='boldStuff'>dude</b> </p> <input type='button' onclick='changeText()' value='Change Text'/> </form> </body> </html> 336
  • 337. 337
  • 338. 338
  • 339. Updating Text Based on User Input 339
  • 340. <script type="text/javascript"> function changeText2() { var userInput = document.getElementById('userInput').value; document.getElementById('boldStuff2').innerHTML = userInput; } </script> <p>Welcome to the site <b id='boldStuff2'>dude</b> </p> <input type='text' id='userInput' value='Enter Text Here'> <input type='button' onclick='changeText2()' value='Change Text'/> 340
  • 341. 341
  • 342. 342
  • 343. <html> <head> <script type="text/javascript">cc=0 function changeimage() {If (cc==0) {cc=1 document.getElementById('myimage').src="bulbon.gif" }else {cc=0 document.getElementById('myimage').src="bulboff.gif" 343
  • 344. 344
  • 345. 345
  • 347. DHTML is NOT a W3C Standard DHTML stands for Dynamic HTML. DHTML is not a standard defined by the World Wide Web Consortium (W3C). DHTML is a "marketing term" - used by Netscape and Microsoft to describe the new technologies the 4.x generation browsers would support. DHTML is a combination of technologies used to create dynamic Web sites. To most people DHTML means a combination of HTML 4.0, Style Sheets and JavaScript. W3C once said: "Dynamic HTML is a term used by some 347
  • 349. <html><head><style> h1.ex1{ position:relative; left:20px;} h1.ex2{ position:relative; left:-20px;} </style></head><body> <h1>Normal Heading</h1> <h1 class="ex1">Heading +20</h1> <h1 class="ex2">Heading -20</h1> <p> Relative positioning moves an element relative to its original position. 349
  • 350. 350
  • 351. <html><head><style> h1.x{ position:absolute; left:100px; top:150px; }</style></head><body> <h1 class="x">This is a heading</h1> <p>With absolute positioning, an element can be placed anywhere on a page.</p> <p>The LEFT position of the heading is 100 pixels from the left of the page. The TOP position is 150 pixels from the top of the 351
  • 352. 352
  • 353. DHTML Document Object Model 353
  • 354. <html> <body> <h1 id="header">My header</h1> <script type="text/javascript"> document.getElementById('header').style.color="red" </script> <p><b>Note:</b> It is the script that changes the style of the element!</p> </body></html> 354
  • 355. 355
  • 358. 358
  • 359. <html><body> <p>Move the mouse over the words to see the cursor change</p> <span style="cursor: auto">Auto</span><br /> <span style="cursor: crosshair">Crosshair</span><br /> <span style="cursor: default">Default</span><br /> <span style="cursor: pointer">Pointer</span><br /> <span style="cursor: hand">Hand</span><br /> <span style="cursor: move">Move</span><br /> <span style="cursor: e-resize">e-resize</span><br /> <span style="cursor: ne-resize">ne-resize</span><br /> <span style="cursor: nw-resize">nw-resize</span><br /> <span style="cursor: n-resize">n-resize</span><br /> <span style="cursor: se-resize">se-resize</span><br /> <span style="cursor: sw-resize">sw-resize</span><br /> <span style="cursor: s-resize">s-resize</span><br /> <span style="cursor: w-resize">w-resize</span><br /> <span style="cursor: text">text</span><br /> <span style="cursor: wait">wait</span><br /> <span style="cursor: help">help</span><br /> </body></html> 359
  • 360. 360
  • 362. 362
  • 363. <html><head><script type="text/javascript"> function blinking_header() { if (!document.getElementById('blink').style.color) {document.getElementById('blink').style.color="red" } if (document.getElementById('blink').style.color=="red") {document.getElementById('blink').style.color="black"} else{document.getElementById('blink').style.color="red"} timer=setTimeout("blinking_header()",100)} function stoptimer(){clearTimeout(timer)} 363
  • 364. 364
  • 366. 366
  • 368. 368
  • 369. <html><head> <script type="text/javascript"> var i=0 txt=new Array("trailA","trailB","trailC") function cursor(interval){ pos=i*8+5 if (interval=='first'){i=0} if (i==0){ xpos=event.clientX ypos=event.clientY document.all(txt[i]).style.visibility="visible " document.all(txt[i]).style.position="absolu te" document.all(txt[i]).style.left=xpos+5 document.all(txt[i]).style.top=ypos+5 } 369
  • 370. 370
  • 371. <html><head><script type="text/javascript"> var c=0 var t function timedCount() { document.getElementById('txt').value=c c=c+1 t=setTimeout("timedCount()",1000) } function stopCount() { clearTimeout(t) } </script></head><body><form> 371