Beruflich Dokumente
Kultur Dokumente
Developers Notes
JavaScript is a client side programming language (runs from the users browser). This means
it has very little awareness of the server environment. For example it can not list directories or
search for files (PHP is used for this). JavaScript was designed to give intelligent dynamic
programming ability to an otherwise static html document.
Notes:
_____________________________________________________________
______________________________________________________________
______________________________________________________________
______________________________________________________________
______________________________________________________________
______________________________________________________________
______________________________________________________________
______________________________________________________________
______________________________________________________________
______________________________________________________________
______________________________________________________________
______________________________________________________________
______________________________________________________________
______________________________________________________________
______________________________________________________________
______________________________________________________________
______________________________________________________________
______________________________________________________________
______________________________________________________________
______________________________________________________________
______________________________________________________________
______________________________________________________________
______________________________________________________________
______________________________________________________________
______________________________________________________________
NeatInfo.com by Jan Zumwalt
JavaScript Reference
Pg 2 of 36
Table of Contents
Where To Put JavaScript .......................................................................................................... 5
Comment ................................................................................................................................... 5
Alert, Confirm, Prompt .............................................................................................................. 6
Alert ........................................................................................................................................................... 6
Confirm ...................................................................................................................................................... 6
Prompt ....................................................................................................................................................... 6
Objects .................................................................................................................................... 11
Reference: ............................................................................................................................................... 11
Methods: .................................................................................................................................................. 11
Arrays ...................................................................................................................................... 16
Buttons .................................................................................................................................... 17
Standard Buttons ..................................................................................................................................... 17
href links .................................................................................................................................................. 18
anchors .............................................................................................................................................. 18
link to internal or external anchor ....................................................................................................... 18
Alerts .................................................................................................................................................. 18
Others ................................................................................................................................................ 18
PHP button use ........................................................................................................................................ 18
Pg 3 of 36
Pg 4 of 36
Comment
// single line comment
/* this is
Pg 5 of 36
A multi-line
Comment
*/
Alert
alert("This is all I have to say!")
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 supplies the user with a choice; they can either
press OK to confirm the popup's message or they can press cancel and not agree to the popup's request.
Here is an example of using confirm to provide a choice to leave or stay.
<html>
<head>
<script type="text/javascript">
function confirmation() {
answer = confirm("Do you want to leave test.com?")
if (answer){
alert("OK! Good by!")
window.location = "http://www.somewhere.com/";
}else{
alert("Thanks for staying!")
}
}
</script>
</head>
<body>
<form>
<input type="button" onclick="confirmation()" value="Leave test.com?">
</form>
</body>
</html>
Prompt
The prompt() is a method of the window object, just like alert() or confirm(). In addition to the "OK" and "Cancel" buttons, a
prompt box also has a text field that can get user input.
name = prompt("Message", "What is your name?");
The prompt occurs as soon as the code is reached, so prompts are usually kept in a function for better control.
Pg 6 of 36
Variables
var url
sum_total
bignum1
smallnum2
some_num
states
=
=
=
=
=
=
"http://www.test.com/";
2001;
3.0e10;
6.023e-23;
34e1;
new Array();
a string value
integer
3.0 X 10^10
6.023 X 10^-23
34 X 10^1
create array variable
Strings
Concatenation
first_name = "Johnny";
last_name = "Bravo";
full_name = first_name + last_name;
result: JonnyBravo
full_name = first_name + " " + last_name; result: Jonny Bravo
page = "15";
page2 = page + 1;
\n:
\t:
\r:
\b:
\f:
\':
\":
\\:
Inserts a new line and causes the text following it to be placed on that line.
Inserts a tab
Carriage return
Backspace
Form feed
Single quote
Double quote
Backslash
String replace
<script type="text/javascript">
visitorName = "Chuck";
myOldString = "Hello username! I hope you enjoy your stay username.";
myNewString = myOldString.replace("username", visitorName);
document.write("Old string = " + myOldString);
document.write("<br />New string = " + myNewString);
</script>
Pg 7 of 36
Result:
Old string = Hello username! I hope you enjoy your stay username.
New string = Hello Chuck! I hope you enjoy your stay username.
b = SOME STRING
b = some string
b = 11, the length of the string
Pg 8 of 36
Math
Order of precedence
The increment and decrement operators can be used either before or after a variable as in:
a++;
b--;
OR
++a;
--b;
same as
same as
a = a + 1;
b = b - 1;
When these operators are used as prefixes, JavaScript first adds one to the variable and then returns the value.
When used as suffixes, the value is first returned and then the variable is incremented. Let's know more about
this:
a = 5;
b = a++;
same as
b = a, a = a + 1
a = 5;
b = ++a;
same as
b = a + 1, a = a + 1
Result: b = 5, a = 6
Result: b = 6, a = 6
Math functions
Remainder a = 70 % 16;
Result: a = 6, because 70/16 = 4r6
Random
a = Math.random();
Result: a = 0 to 1
Round up
a = Math.ceil(2.156) Result: a = 3
Round Down a = Math.floor(2.456) Result: a = 2
abs
absolute value
sin, cos, tan
standard trigonomic functions
acos, asin, atan
min, max
returns max/min value of to arguments
round
rounds argument
sqrt
square root
pow
exponential; first arg base, second arg exponent
Shorthand Notation
Operator
Meaning
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
x >>= y
x >>= y
x >>>= y
x = x >>> y
x &= y
x=x&y
x ^= y
x=x^y
x |= y
x=x|y
Operator type
Individual operators
Operator Precedence
member
. []
() new
negation/increment
Pg 9 of 36
multiply/divide
*/%
addition/subtraction
+-
bitwise shift
relational
equality
== != === !==
bitwise-and
&
bitwise-xor
bitwise-or
logical-and
&&
logical-or
||
conditional
?:
assignment
comma
Comparison Operators
Operator
Description
Example
==
is equal to
5 == 8 returns false
===
X=5
y = "5"
x == y returns true
x === y returns false
!=
is not equal
5 != 8 returns true
>
is greater than
<
is less than
>=
<=
Logical Operators
Operator
Description
Example
&&
and
X =6
y =3
(x < 10 && y > 1) returns true
||
or
X =6
y =3
not
(x == 5 || y == 5) returns false
X=6
y=3
!(x==y) returns true
Pg 10 of 36
Objects
Javascript is an object orientated language which means that windows and buttons (objects) have properties
and methods (actions) that can be used. A window (object) has size and color (properties), and can be
opened, minimized and closed (methods).
Reference:
When we want to refer to an object, its properties or methods, we use a dot (.) to show the hierarchy.
To use a document object we use the following notation:
window.document
To use a HTML Form called contactform inside the document
window.document.contactform
A textfield inside the contact form named address
window.document.contactform.address
Or a button called newcontact inside the contact form
window.document.contactform.newcontact
Methods:
Objects such as the address textfield we used above have methods that allow use to manipulate them. The textfield has the
following methods
name: specifies the text field name
value: specifies its value (the text contained in the field)
defaultValue: determines the default text value
type: identifies its type
To set the text in the address field we can also use methods made available through inheritance of the document parent.
One of these methods is add. So here is how we put text into the address textfield.
document.contactform.add.value = "Type your address here";
Alert Message:
Show a popup message
window.alert("I am an alert box");
we dont have to show the base object so
alert("I am an alert box");
The alert popup message is used so much that we include some of the text properties that can be included.
Pg 11 of 36
\n:
\t:
\r:
\b:
\f:
\':
\":
\\:
Inserts a new line and causes the text following it to be placed on that line.
Inserts a tab
Carriage return
Backspace
Form feed
Single quote
Double quote
Backslash
Event Handlers
Attribute Description
onAbort
onblur
run when an element loses focus
onChange
run when an element change
onClick
run on a mouse click
onDblClick run on a mouse double-click
onDragDrop
onError
onFocus
run when an element gets focus
onKeyDown run when a key is pressed
onKeyPress run when a key is pressed and released
onKeyUp
run when a key is released
onLoad
onMouseDown run when mouse button is pressed
onMouseMove run when mouse pointer moves
onMouseOut run when mouse pointer moves out of an element
onMouseOver run when mouse pointer moves over an element
onMouseUp run when mouse button is released
onMove
onReset
onResize
onSelect
onSubmit
onUnload
Change the document background color and put a message on the status bar.
<A HREF="http://www.webdevelopersnotes.com/" onmouseover="window.status='Go Back To Home Page';
document.bgColor='#EEEEEE'"> Change background color and put a message on the status bar</A>
Functions
Syntax
<SCRIPT LANGUAGE="JavaScript" TYPE="TEXT/JAVASCRIPT">
function alert_box() {
Pg 12 of 36
How to call it
<A HREF="javascript:void(0)"
<A HREF="javascript:void(0)"
Another way to describ the
<A HREF="javascript:void(0)"
onmouseover="change_back('#ff0000')">Red background</A>
onmouseover="change_back('#00ff00')">Green background</A>
color
onmouseover="change_back('blue')">Blue background</A>
Return
This flow of execution can be stopped by including a return statement, which causes the function to return a value, hence
the statements after return are not executed. Its syntax is:
return
return
return
return
return
expression
$name
false
favorite color is blue
1000
Pg 13 of 36
}else if (condition) {
Do this instead
}else{
Do this instead
}
The IF statement is often combined with the || (or), or the && (and) comparisons. The following code will act on
all numbers except those in the range of 20 and 50.
if (number < 20 || number > 50) {
alert("...");
}
Similarly, the && allows a range; for example the following code only acts on numbers 100 thru 149
if (number > 99 && number < 150) {
alert("...");
}
Pg 14 of 36
For Loop
Syntax
for (initialization; condition; increment) {
... statements ...
}
As long as the condition evaluates to 'true', the program execution will continues to loop through the statements.
Here is a while loop to print out 10 numbers.
msg = "";
x = 1;
while (x <= 10) {
msg = msg + x + "\n";
x++;
}
alert(msg);
You can consider the do-while loop as a modified version of the while loop. Here, the condition is placed at the
end of the loop so that the loop always executes at least once.
msg = "";
x = 1;
do {
msg = msg + x + "\n";
x++;
}
while (x <= 10);
alert(msg);
In the code above, the value of variable x is 10, hence the condition evaluates to 'false'. However, the loop is
executed once since the condition is presented at the end of the loop and not at the beginning.
NeatInfo.com by Jan Zumwalt
JavaScript Reference
Pg 15 of 36
This will only print even numbers. It checks to see if the number can be evenly divided by 2.
msg = "";
for (var x = 0; x <=20; x++) {
if (x%2) { continue; }
msg = msg + x + "\n";
}
alert(msg);
Arrays
An array is group of variables that can be acted on together. Each member of the array can be referred to by a number
usually called the index or key (it is how we will access the variables). The number may also be given an English alias
name (humans remember names better than numbers).
Consider this example
Number (key)
Value
Smith
Baxter
Johnson
Javascript is smart enough to assign the index numbers 0 through 2 to the names.
We can use the index number with a loop to print them.
for (x = 0; x < 2; x++) {
document.write(names[x] + "\n");
}
Now can write a generic loop to print all elements to an array of unknown size.
array_length = names.length;
for (x = 0; x < array_length; x++) {
document.write(names[x] + "\n");
}
Pg 16 of 36
Buttons
Standard Buttons
<html>
<head>
<title>Javascript Buttons</title>
<script type="text/javascript">
// How to use the confirm button
function confirm_button() {
var answer = confirm("Press a button");
if (answer==true) {
alert("You pressed OK!");
}else{
alert("You pressed Cancel!");
}
}
// How to use the prompt input
function prompt_button() {
var answer = prompt("Enter your name","Default text");
if (answer!=null && answer!="") {
alert("Your name is " + answer + "! How are you today?");
}
}
</script>
</head>
<body style="font-family:arial;">
<table cellspacing=30px>
<tr><td>
Change browser status bar<br>
<INPUT type="button" value="Status bar"
name="button1" onClick="window.status='You clicked the button!'; return true"><br>
Go to a wb page<br>
<INPUT type="button" value="Go to a URL"
name="button2" onClick="window.location='http://www.test.com'"><br>
Here is a back button<br>
<INPUT type="button" value="Go back"
name="button3" onClick="history.back()"><br> <!-- number in parenthesis is how many pages -->
Here is a forward button<br>
<INPUT type="button" value="Go forward"
name="button4" onClick="history.forward()"><br> <!-- number in parenthesis is how many pages -->
</td><td>
An alert button<br>
<INPUT type="button" value="Don't click!"
name="button5" onClick="alert('Hey! I said not to click!')" /><br>
Confirm function button<br>
<input type="button" value="Confirm"
name="button6" onclick="confirm_button()"
/><br>
/><br>
Pg 17 of 36
href links
anchors
Name an internal anchor
<A NAME="redirect">Meta Refresh Tag</A>
Alerts
<A HREF="#TOC" onClick="(alert('this will take you to the top!'))">To the Table of Contents</A>
<A HREF="#TOC" onClick="(confirm('this will take you to the top!'))">To the Table of Contents</A>
<A HREF="#TOC" onClick="(x=prompt('enter name: ', 'Default Text'))">To the Table of Contents</A>
Others
Backlink
<A HREF="javascript:history.back()">Back</A>
Redirect
<META HTTP-EQUIV="refresh" CONTENT="7;
url=http://funnelweb.utcc.utk.edu/~dmdragon/merchant/links.htm#redirect">
Mouse over
<A HREF="#TOC" onMouseOver="window.status='this will take you to the top!'; return true">To the
Table of Contents</A>
name="action" onClick="window.location=\'add-del-
name="action" onClick="window.location=\'add-del-
Pg 18 of 36
-->
<SCRIPT language="JavaScript">
over
= new Image();
over.src
= "bt-over.jpg";
down
= new Image();
down.src
= "bt-down.jpg"
normal
= new Image();
normal.src = "bt-normal.jpg";
function changeImage() {
document.images["jsbutton"].src= over.src;
return true;
}
function changeImageBack() {
document.images["jsbutton"].src = normal.src;
return true;
}
function handleMDown() {
document.images["jsbutton"].src = down.src;
return true;
}
function handleMUp() {
changeImage();
return true;
}
</SCRIPT>
</body>
</html>
Pg 19 of 36
We can now call this function from our even handlers and pass it the two arguments.
<a HREF="some.html" onmouseover="roll_over('but1', 'icon2.gif')"
onmouseout="roll_over('but1', 'icon1.gif')"><IMG SRC="icon1.gif" WIDTH="100" HEIGHT="50"
NAME="but1" BORDER="0"></a>
List Boxes
Selection lists are quite commonly used in forms-with some help from JavaScript, it can be very useful
sometimes.
The fundamental way to access forms is through its name. Accessing selection lists are no different. Here's an
example:
<form name="box1">
<p><select name="example" size="1">
<option>choice1</option>
<option>choice2</option>
<option>choice3</option>
<option>choice4</option>
</select></p>
</form>
Accessing selection lists in JavaScript can be quite confusing. Where's the confusion, you ask? Well, the above
line will access only the selection list itself, and not the individual elements. We have to go deeper to do that.
Lets discuss how this is done.
Pg 20 of 36
JavaScript gives us access to the individual elements (choice1, choice 2, choice 3 etc) by using the options
array. An array is a series of variables all with the same name, but with different index numbers. (More on this in
the future). This is, however, all you're need to know about arrays to access selections.
Ok, lets assume we want to access the first element of this selection list:
document.box1.example.options[0]
//gives us access to element "choice1"
This will give us direct access to the first element of the selection list.
To access the third element, we would do this:
document.box1.example.options[2]
//gives us access to element "choice3"
It doesn't take a rocket scientist to realize that the number inside the [ ] are always "1" minus the actual position
of the element in the list. ALL ARRAYS BEGIN WITH INDEX NUMBER "0", NOT "1"
So, now that we know the way to get to these little rats, lets see some properties we can use with them:
Properties for elements of options array
properties
description
text
value
Lets say we want to alert the name of the first element (in this case, the name is "choice1"):
choice1
onClick="alert(document.box1.example.options[0].text)"
And lets say we want to know the value that's associated with this element:
onClick="alert(document.box1.example.options[0].value)"
I know selection lists are a mess, but that's the way they are accessed...
We now know how to access each of the elements within the selection list...but only by hard-coding the index
number into the script. For example, we still have no way of telling our script to alert the value of each element,
depending on what he/she has selected. We will now proceed to learn how we can have scripts automatically
update itself whenever a different selection is made by the user, and see some practical uses of this.
Pg 21 of 36
description
returns the actual text (name) of the element
returns the value of the element
description
tells us the number of elements within this selection list
tells us the index number of the selected option
Using the above table, to use the properties, we would do the following:
document.formname.selectionname.options.property
Using the length property, we can see how many elements are in the selection list:
alert(document.box1.example.options.length)
As you can see, it alerts "3", since there are three elements in the list.
The selectedIndex property informs the index number of the element selected, and updates itself
whenever a new selection is made.
For example:
Make a selection:
choice1
onClick="alert(document.box1.example.options.selectedIndex)"
The selectedIndex property updates itself if you change elements, so if you had selected "choice1", it alerts "0"
(since array indexes start at 0), if you than changed and selected "choice2", it will alert "1" instead. The example
above may not seem like much, but it paves the way for many useful scripts.
Pg 22 of 36
Before we plunge right in, lets first put together all our ideas we've learned in Lesson15 and 16. Recall from
Lesson 15, that to access the individual elements, we would write:
document.box1.example.options[x]
Now, with the above two pieces of code, we are all set to make our combo box script!
Cnet
<form name="box1">
<p><select name="example" size="1">
<option value="http://www.cnet.com">choice1</option>
<option value="http://www.cnn.com">choice2</option>
<option value="http://www.geocities.com">choice3</option>
</select></p>
<script language="javascript">
function go()
{
location=document.box1.example.
options[document.box1.example.selectedIndex].value
}
</script>
<input type="button" name="test" value="Go!" onClick="go()">
</form>
Pay close attention to how we put together the two pieces of code mentioned earlier:
location=
document.box1.example.options[document.box1.example.selectedIndex].value
See, the part in red, the script that returns the index of the element selected, is put inside the script that returns
the value of that particular element. Now, since the "red" script is a self updating script that automatically
changes index numbers whenever a user selects another element, the "blue" script will in turn always get the
value (url) of the element the user has selected.
The above only illustrates one of the many uses of selection lists...the fun of it all is using your creativity with
JavaScript and "doing your own thing."
Pg 23 of 36
*******************************************************
* Pop-it menu- Dynamic Drive (www.dynamicdrive.com) *
*******************************************************
*/
Pg 24 of 36
onClick="my_function($my_var)">View/Edit File</a>'
linkset[0]+='<a href="#" onClick="my_function($my_var)">Move File</a>'
linkset[1]='<font color=red><center><b>Actions</b></center></font>' // sub-heading
linkset[1]+='<hr>' //Optional Separator
linkset[1]+='<a href="http://www.javascriptkit.com">JavaScript Kit</a>'
linkset[1]+='<a href="http://www.codingforums.com">Coding Forums</a>'
linkset[1]+='<a href="http://www.cssdrive.com">CSS Drive</a>'
linkset[1]+='<a href="http://freewarejava.com">Freewarejava</a>'
////No need to edit beyond here
var ie5=document.all && !window.opera
var ns6=document.getElementById
if (ie5||ns6)
document.write('<div id="popitmenu" onMouseover="clearhidemenu();"
onMouseout="dynamichide(event)"></div>')
function my_function(){
alert("hello world!"+$my_var)
}
function iecompattest(){
return (document.compatMode && document.compatMode.indexOf("CSS")!=-1)? document.
documentElement : document.body
}
function showmenu(e, which, selectelement, optWidth){
$my_var = selectelement.options[selectelement.selectedIndex].value
if (!document.all&&!document.getElementById)
return
clearhidemenu()
menuobj=ie5? document.all.popitmenu : document.getElementById("popitmenu")
menuobj.innerHTML=which
menuobj.style.width=(typeof optWidth!="undefined")? optWidth : defaultMenuWidth
menuobj.contentwidth=menuobj.offsetWidth
menuobj.contentheight=menuobj.offsetHeight
eventX=ie5? event.clientX : e.clientX
eventY=ie5? event.clientY : e.clientY
//Find out how close the mouse is to the corner of the window
var rightedge=ie5? iecompattest().clientWidth-eventX : window.innerWidth-eventX
var bottomedge=ie5? iecompattest().clientHeight-eventY : window.innerHeight-eventY
//if the horizontal distance isn't enough to accomodate the width of the context menu
if (rightedge<menuobj.contentwidth)
//move the horizontal position of the menu to the left by it's width
menuobj.style.left=ie5? iecompattest().scrollLeft+eventX-menuobj.contentwidth+"px" :
window.pageXOffset+eventX-menuobj.contentwidth+"px"
else
//position the horizontal position of the menu where the mouse was clicked
menuobj.style.left=ie5? iecompattest().scrollLeft+eventX+"px" : window.pageXOffset+eventX+"px"
//same concept with the vertical position
if (bottomedge<menuobj.contentheight)
menuobj.style.top=ie5? iecompattest().scrollTop+eventY-menuobj.contentheight+"px" :
window.pageYOffset+eventY-menuobj.contentheight+"px"
else
menuobj.style.top=ie5? iecompattest().scrollTop+event.clientY+"px" :
window.pageYOffset+eventY+"px"
menuobj.style.visibility="visible"
return false
}
Pg 25 of 36
function contains_ns6(a, b) {
//Determines if 1 element in contained in another- by Brainjar.com
while (b.parentNode)
if ((b = b.parentNode) == a)
return true;
return false;
}
function hidemenu(){
if (window.menuobj)
menuobj.style.visibility="hidden"
}
function dynamichide(e){
if (ie5&&!menuobj.contains(e.toElement))
hidemenu()
else if (ns6&&e.currentTarget!= e.relatedTarget&& !contains_ns6(e.currentTarget,
e.relatedTarget))
hidemenu()
}
function delayhidemenu(){
delayhide=setTimeout("hidemenu()",500)
}
function clearhidemenu(){
if (window.delayhide)
clearTimeout(delayhide)
}
if (ie5||ns6)
document.onclick=hidemenu
</script>
target="windowname"
Pg 26 of 36
Example 2:
The open() takes arguments. When used without any arguments, the new window displayed is blank.
<A HREF="javascript:void(0)" onclick="window.open('welcome.html')"> Open a new window</A>
NAME:
Specifies a name for the new window that can then be used as value for the TARGET attribute of <A>
tags.
FEATURES: Lets you define properties of the window such as width, height, presence or absence of scrollbars, location
bar, status bar etc. The list of features is quite daunting so we shall go over them gradually.
REPLACE: A boolean value... we won't bother ourselves with this argument!
height:
width:
location:
menubar:
scrollbars:
status:
toolbar:
directories:
resizable:
fullscreen:
The width and the height take a number (pixels) as value, for other features the value is either a yes or no.
Example 3:
This opens a new window 300 pixels in width and 200 pixels in height. It doesnt have scrollbars, a location bar,
status bar, menubar, toolbar or buttons!
Notice that the two features (width and height) are enclosed by a pair of quotes without any spaces and there
are no quotes surrounding the values.
<A HREF="javascript:void(0)" onclick="window.open('welcome.html',
'welcome','width=300,height=200')">Open a new window</A>
Note: in this (and others) example the entire JavaScript code (method) should be placed on a single line.
Example 4:
This window has the menu and the status bars. The others are absent since we didn't specify them.
Pg 27 of 36
<A HREF="javascript:void(0)"
onclick="window.open('welcome.html','welcome','width=300,height=200,menubar=yes,status=yes')">
Open a new window</A>
Example 5:
In this example we want to specify a width and height, that forces us to include the other options.
<A HREF="javascript:void(0)" onclick="window.open('welcome.html','welcome','width=300,
height=200,menubar=yes,status=yes,location=yes,toolbar=yes,scrollbars=yes')">Open a new window</A>
Example 6:
Here is a small novelty for Internet Explorer users. The fullscreen feature can only be used with IE browsers
and displays the document on the entire screen. A neat effect... sort of! Click on the F11 to remove the full
screen display.
<A HREF="javascript:void(0)" onclick="window.open('welcome2.html',
'welcome','fullscreen=yes,scrollbars=yes')">Open a full screen window</A>
Example 7:
Using a function to open a new window. We name this function open_win and place it in the HTML head section.
<head>
function open_win() {
window.open('welcome.html','welcome','width=300,height=200,
menubar=yes,status=yes,location=yes, toolbar=yes,scrollbars=yes');
}
</head>
Example 8:
One function for many URLs.
function open_win(url_add)
{
window.open(url_add,'welcome','width=300,height=200,menubar=yes,status=yes,
location=yes,toolbar=yes,scrollbars=yes');
}
The function has a parameter url_add inside the parenthesis. It occurs in the function once again at the place
where we specify the URL for the new window, however, this time it's not enclosed in quotes.
To call the open_win function, we pass an argument which is the url address of the document we plan to display
in the new window.
open_win("welcome.html");
Pg 28 of 36
onclick="open_win('welcome.html')">Welcome message</A>
Regex
Syntax
var regex = /pattern/modifiers;
Patterns
^ start of string
$ end of string
. any single character
(a|b)
a or b
()
series or group
[abc]
contains or in range
[^abc]
does not contain or is in the range
a?
zero or one of a
a+
one or more of a
a{3}
exactly 3 a
a{3,}
3 or more a
a{3,6}
between 3 and 6 a
!(pattern) not a match
Modifiers
/g
global, all occurrences
/i
case sensitive
/s single line mode
/m multi-line, match spans across lines
General Snippets
It is best to use single quotes for JavaScript and double quotes for embedded html.
<SCRIPT LANGUAGE="JAVASCRIPT" TYPE="TEXT/JAVASCRIPT">
document.write('<FONT COLOR="#0000FF">Blue denim</FONT>');
</SCRIPT>
Browser detection
Javascript keeps track of browser information using the navaigator object
navigator.appName - Gives the name of the browser (application Name)
navigator.appVersion
- Gives the browser version (application Version)
navigator.appCodeName
- Gives the browser codename (application CodeName)
navigator.platform - Gives the platform on which the browser is running
Pg 29 of 36
window.location="netscape_version.html";
}
</SCRIPT>
Thus, variable d contains a new date object. We can now call the various methods of this date object.
var
var
var
var
var
var
var
t_date = d.getDate();
t_mon = d.getMonth();
t_year = d.getFullYear();
t_hour = d.getHours();
t_min = d.getMinutes();
t_sec = d.getSeconds();
t_mil = d.getMilliseconds;
//
//
//
//
//
//
//
Returns
Returns
Returns
Returns
Returns
Returns
Returns
Now we can easily display the date, month and year in an alert box , using the values stored in respective variables.
alert("Today's date is " + t_date + "-" + t_mon + "-" + t_year);
Print page
If you click this button you should be prompted with whatever application your computer uses to handle its print
functionality.
<form>
<input type="button" value="Print This Page" onClick="window.print()" />
</form>
Redirect
By setting window.location equal to a new URL, you will change the current webpage to the one that is specified.
<script type="text/javascript">window.location = "http://www.test.com/"</script>
Pg 30 of 36
Toggle ID Visibility
ID selectors allow us to identify a unique element on the web page. Remember that a CLASS can be used many
times. But a ID may only be used one time on a page. You write an ID selector in exactly the same way that
you use the Class selectors. The only difference is the spelling of the word CLASS vs ID.
<DIV ID = FontOne>Hello world text</DIV>
Why would we need an ID selector? A scripting language may want to cause something to happen such as a
color to change or something to appear or disappear. The script language will control the page element by
referring to its ID name.
We now present a script that allows the title of our web page to either change
its visibility (its there, we just wont see it), or to entirely remove it from, or add it
to the web page.
<HTML>
<HEAD>
<TITLE>CSS Style Example</TITLE>
<STYLE TYPE = "text/css">
body { font-family: arial; }
p
{ font-style: italic; color: #059; }
h1
{ color: red; }
h2
{ color: blue; font-size:12pt; }
</STYLE>
<script type="text/javascript">
// toggles visibility of element ID passed to this function, hidden/visible
function toggleVisibility(x) {
if(document.getElementById(x).style.visibility == "hidden" ) {
document.getElementById(x).style.visibility = "visible";
}
else {
document.getElementById(x).style.visibility = "hidden";
}
}
// toggles existence of element ID passed to this function, added/removed from page
function toggleExistance(x) {
if(document.getElementById(x).style.display == "none" ) {
document.getElementById(x).style.display = "";
}
else {
document.getElementById(x).style.display = "none";
}
}
</script>
</HEAD>
<BODY>
<h1 ><div id="toggleMe" style="visibility: visible;display=''">Nursery Rhyme</div></h1>
<h2>Mary Had A Little Lamb</h2>
Pg 31 of 36
<h3>First stanza</h3>
<p> Mary had a little lamb,<br>
Its fleece was white as snow;<br>
And everywhere that Mary went,<br>
The lamb was sure to go.</p>
<h3>Second stanza</h3>
<p> He followed her to school one day,<br>
Which was against the rule;<br>
It made the children laugh and play<br>
To see a lamb at school.</p>
<a href="#" onclick="toggleVisibility('toggleMe');">[ Toggle Visibility ]</a> 
<a href="#" onclick="toggleExistance('toggleMe');">[ Toggle Display ]</a>
</body>
</HTML>
When you click on one of the links at the bottom, it causes one of the javascript routines to be run and changes
the visibility or existence of the page title that we gave a ID=toggleMe.
Pg 32 of 36
getFullYear
getHours
getMilliseconds
getMinutes
getMonth
getSeconds
getTime
getTimezoneOffset
getYear
setDate
setHours
setMilliseconds
setMinutes
setMonth
setSeconds
setYear
toLocale TimeString
Pg 33 of 36
Form
submit
DOM Collections
item
Range
Collapse
createContextualFragment
moveEnd
moveStart
parentElement
select
setStarBefore
Style
getPropertyValue
setPropertyValue
Event
initEvent
preventDefault
stopPropegation
XML
serilizeToString
open
send
loadXML
Parser
parseFromString
Window
Alert
Blur
clearTimeout
close
focus
open
print
setTimeout
Built In
Eval
parseInt
parseFloat
isNaN
isFinite
decodeURI
decodeURIComponent
encodeURI
encodeURIComponent
excape
unexcap
Notes:
_____________________________________________________________
______________________________________________________________
______________________________________________________________
______________________________________________________________
______________________________________________________________
______________________________________________________________
______________________________________________________________
______________________________________________________________
______________________________________________________________
______________________________________________________________
______________________________________________________________
______________________________________________________________
______________________________________________________________
______________________________________________________________
______________________________________________________________
______________________________________________________________
______________________________________________________________
______________________________________________________________
______________________________________________________________
______________________________________________________________
______________________________________________________________
______________________________________________________________
______________________________________________________________
______________________________________________________________
______________________________________________________________
______________________________________________________________
NeatInfo.com by Jan Zumwalt
Pg 34 of 36
Copyright 2005-2012
Notes:
_____________________________________________________________
______________________________________________________________
______________________________________________________________
______________________________________________________________
______________________________________________________________
______________________________________________________________
______________________________________________________________
______________________________________________________________
______________________________________________________________
______________________________________________________________
______________________________________________________________
______________________________________________________________
______________________________________________________________
______________________________________________________________
______________________________________________________________
______________________________________________________________
______________________________________________________________
______________________________________________________________
______________________________________________________________
______________________________________________________________
______________________________________________________________
______________________________________________________________
______________________________________________________________
______________________________________________________________
______________________________________________________________
______________________________________________________________
NeatInfo.com by Jan Zumwalt
Pg 35 of 36
Copyright 2005-2012
Back Page
Tutorials
http://www.w3schools.com/js/default.asp
://www.w3schools.com/js/default.asp
http://www.pageresource.com/jscript/
http://www.tizag.com/javascriptT/
References
http://www.w3schools.com/jsref/default.asp
http://www.devguru.com/technologies/ecmascript/quickref/javascript_index.html
http://www.d.umn.edu/itss/training/online/webdesign/javascript.html
Pg 36 of 36
Copyright 2005-2012