of 36
8/3/2019 Javascript Referance - Jan Zumwalt
1/36
JavaScript
Developers Notes
JavaScript is a client side programming language (runs from the users browser). This meansit has very little awareness of the server environment. For example it can not list directories orsearch for files (PHP is used for this). JavaScript was designed to give intelligent dynamicprogramming ability to an otherwise static html document.
This and many other developer references available at http:/neatinfo.com/dev_notes/_cheat-sheets
8/3/2019 Javascript Referance - Jan Zumwalt
2/36
NeatInfo.com by Jan Zumwalt May 27, 2012JavaScript Reference Copyright 2005-2012
Pg 2 of 36
Notes:
_____________________________________________________________
______________________________________________________________
______________________________________________________________
______________________________________________________________
______________________________________________________________
______________________________________________________________
______________________________________________________________
______________________________________________________________
______________________________________________________________
______________________________________________________________
______________________________________________________________
______________________________________________________________
______________________________________________________________
______________________________________________________________
______________________________________________________________
______________________________________________________________
______________________________________________________________
______________________________________________________________
______________________________________________________________
______________________________________________________________
______________________________________________________________
______________________________________________________________
______________________________________________________________
______________________________________________________________
______________________________________________________________
8/3/2019 Javascript Referance - Jan Zumwalt
3/36
NeatInfo.com by Jan Zumwalt May 27, 2012JavaScript Reference Copyright 2005-2012
Pg 3 of 36
Table of Contents
Where To Put JavaScript ...................... ......................... ......................... ...................... ............ 5
Comment ................................................................................................................................... 5
Alert, Confirm, Prompt ........................ ........................ ....................... ......................... .............. 6
Alert ........................................................................................................................................................... 6
Confirm ...................................................................................................................................................... 6
Prompt ....................................................................................................................................................... 6
Variables, Strings, Math ..................... ......................... ....................... ......................... .............. 6
Variables .................................................................................................................................................... 7
Strings ........................................................................................................................................................ 7
Split strings at delimiter ........................................................................................................................ 7
String replace ....................................................................................................................................... 7Global regular expression replace........................................................................................................ 8
Other useful string functions ................................................................................................................ 8
Search Function Regular Expression .................................... ......................... ...................... ... 8
Math ........................................................................................................................................................... 9
Order of precedence ............................................................................................................................ 9
Math functions ...................................................................................................................................... 9
Objects .................................................................................................................................... 11
Reference: ............................................................................................................................................... 11
Methods: .................................................................................................................................................. 11
Alert Message: ........................................................................................................................ 11
Event Handlers ...................... ......................... ......................... ......................... ...................... . 12
Functions ................................................................................................................................ 12
Syntax ...................................................................................................................................................... 12
Return ...................................................................................................................................................... 13
Conditional and Loops Statements .................... ...................... ......................... ..................... 13
IF Else ...................................................................................................................................................... 13
For Loop .................................................................................................................................................. 15
While & Do Loop ...................................................................................................................................... 15
Continue & Break ..................................................................................................................................... 16
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
8/3/2019 Javascript Referance - Jan Zumwalt
4/36
NeatInfo.com by Jan Zumwalt May 27, 2012JavaScript Reference Copyright 2005-2012
Pg 4 of 36
Simple Rollover Button Image (onmouseover) ........................................................................................ 18
Advanced Rollover Button (function)........................................................................................................ 19
Advanced Rollover Button (alternative method) ....................................................................................... 20
List Boxes ............................................................................................................................... 20
Simple List Box ........................................................................................................................................ 20
Accessing Elements Of The List .............................................................................................................. 20
Properties of Option Array ....................................................................................................................... 21
Combo List box ........................................................................................................................................ 23
List Box Processing ................................................................................................................................. 23
ListBox List Popup Menu ......................................................................................................................... 24
Redirection and new windows .................................... ...................... ......................... ............ 26
Regex ....................................................................................................................................... 29
Syntax ...................................................................................................................................................... 29
General Snippets .................................................................................................................... 29
Browser detection .................................................................................................................................... 29
Date & Time ............................................................................................................................................. 30
Check for number .................................................................................................................................... 30
Print page ................................................................................................................................................ 30
Redirect ................................................................................................................................................... 30
Toggle ID Visibility ................................................................................................................................... 31
Method & Function Reference ....................... ......................... ......................... ...................... . 33
Methods ................................................................................................................................................... 33
Doc Methods (DOM) ................................................................................................................................ 33
Window .................................................................................................................................................... 33
Built In ...................................................................................................................................................... 33Back Page ............................................................................................................................... 36
Tutorials ................................................................................................................................................... 36
References .............................................................................................................................................. 36
8/3/2019 Javascript Referance - Jan Zumwalt
5/36
NeatInfo.com by Jan Zumwalt May 27, 2012JavaScript Reference Copyright 2005-2012
Pg 5 of 36
Where To Put JavaScript
Javavscript function in the tag of HTML documents:
Page title
some javascript code...
Home Page
Code...
Javavscript inside a HTML :
Page title
some javascript code...
Home Page
Code...
Javavscript include files:
Page title
some javascript code...
Home Page
Code...
Comment
// single line comment
/* this is
8/3/2019 Javascript Referance - Jan Zumwalt
6/36
NeatInfo.com by Jan Zumwalt May 27, 2012JavaScript Reference Copyright 2005-2012
Pg 6 of 36
A multi-line
Comment
*/
Alert, Confirm, Prompt
Alert, confirm, and prompt are the most often used debugging tools in JavaScript so we start by discussing them.Other examples of buttons are contained in another section.
Alert
alert("This is all I have to say!")
Confirm
The JavaScript confirmfunction is very similar to the JavaScript alertfunction. A small dialogue box pops up andappears in front of the web page currently in focus. The confirm box supplies the user with a choice; they can eitherpress 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.
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!")}
}
PromptThe 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.
Variables, Strings, Math
8/3/2019 Javascript Referance - Jan Zumwalt
7/36
NeatInfo.com by Jan Zumwalt May 27, 2012JavaScript Reference Copyright 2005-2012
Pg 7 of 36
Variables
var url = "http://www.test.com/"; a string value
sum_total = 2001; integer
bignum1 = 3.0e10; 3.0 X 10^
10
smallnum2 = 6.023e-23; 6.023 X 10^
-23
some_num = 34e1; 34 X 10^1
states = new Array(); 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; result: page2 = "151";
\n: Inserts a new line and causes the text following it to be placed on that line.
\t: Inserts a tab
\r: Carriage return
\b: Backspace
\f: Form feed
\': Single quote
\": Double quote
\\: Backslash
Split strings at delimiter
myString = "123456789";
splitResult = myString.split("5");
for(i = 0; i < splitResult.length; i++){
document.write("
Element " + i + " = " + splitResult[i]);
}
Element 0 = 1234
Element 1 = 6789
Notice that the delimiter is not shown
String replace
visitorName = "Chuck";
myOldString = "Hello username! I hope you enjoy your stay username.";
myNewString = myOldString.replace("username", visitorName);
document.write("Old string = " + myOldString);
document.write("
New string = " + myNewString);
8/3/2019 Javascript Referance - Jan Zumwalt
8/36
NeatInfo.com by Jan Zumwalt May 27, 2012JavaScript Reference Copyright 2005-2012
Pg 8 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.
Notice that the second user name was not replaced.
Global regular expression replace
visitorName = "Chuck";
myOldString = "Hello username! I hope you enjoy your stay username.";
myNewString = myOldString.replace(/username/g, visitorName);
document.write("Old string = " + myOldString);
document.write("
New string = " + myNewString);
Result:
Old string = Hello username! I hope you enjoy your stay username.
New string = Hello Chuck! I hope you enjoy your stay Chuck.
Other useful string functionsa = Some string
b = a.toUpperCase(); b = SOME STRING
b = a.toLowerCase(); b = some string
b = a.length; b = 11, the length of the string
Search Function Regular ExpressionRemember when creating a regular expression that it must be surrounded with slashes /regular expression/.Let's search a string to see if a common name "Alex" is inside it.
string1 = "Today John went to the store and talked with Alex.";
RegExp = "/Alex/";
matchPos1 = string1.search(RegExp);
if(matchPos1 != -1) {
document.write("There was a match at position " + matchPos1);
}else{
document.write("There was no match in the string");
}
Result: There was a match at position 45
8/3/2019 Javascript Referance - Jan Zumwalt
9/36
NeatInfo.com by Jan Zumwalt May 27, 2012JavaScript Reference Copyright 2005-2012
Pg 9 of 36
Math
Order of precedenceThe increment and decrement operators can be used either before or after a variable as in:
a++; same as a = a + 1;
b--; same as b = b - 1;
OR
++a;
--b;
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 aboutthis:
a = 5;
b = a++; same as b = a, a = a + 1 Result: b = 5, a = 6
a = 5;
b = ++a; same as b = a + 1, a = a + 1 Result: b = 6, a = 6
Math functionsRemainder 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 % yx >= y
x >>>= y x = x >>> y
x &= y x = x & y
x ^= y x = x ^ y
x |= y x = x | y
Operator Precedence
Operator type Individual operators
member . []
call / create instance () new
negation/increment ! ~ - + ++ -- type of void delete
8/3/2019 Javascript Referance - Jan Zumwalt
10/36
NeatInfo.com by Jan Zumwalt May 27, 2012JavaScript Reference Copyright 2005-2012
Pg 10 of 36
multiply/divide * / %
addition/subtraction + -
bitwise shift > >>>
relational < >= in instance of
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
=== is equal to (checks for both value and type) X = 5y = "5"x == y returns truex === y returns false
!= is not equal 5 != 8 returns true
> is greater than 5 > 8 returns false
< is less than 5 < 8 returns true
>= is greater than or equal to 5 >= 8 returns false
8/3/2019 Javascript Referance - Jan Zumwalt
11/36
NeatInfo.com by Jan Zumwalt May 27, 2012JavaScript Reference Copyright 2005-2012
Pg 11 of 36
Objects
Javascript is an object orientated language which means that windows and buttons (objects) have propertiesand 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 documentwindow.document.contactform
A textfield inside the contact form named addresswindow.document.contactform.address
Or a button called newcontact inside the contact formwindow.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";
Here are some other common examples of using methods.
This prints text in the browser web page
document.write("I Love JavaScript");
This causes myform to be submitted.
document.myform.submit();
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.
8/3/2019 Javascript Referance - Jan Zumwalt
12/36
NeatInfo.com by Jan Zumwalt May 27, 2012JavaScript Reference Copyright 2005-2012
Pg 12 of 36
\n: Inserts a new line and causes the text following it to be placed on that line.
\t: Inserts a tab
\r: Carriage return
\b: Backspace
\f: 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 background color of the document.
Home Page
Show an alert message over the link
Home Page
Change the document background color and put a message on the status bar.
Change background color and put a message on the status bar
Functions
Syntax
function alert_box() {
8/3/2019 Javascript Referance - Jan Zumwalt
13/36
NeatInfo.com by Jan Zumwalt May 27, 2012JavaScript Reference Copyright 2005-2012
Pg 13 of 36
alert("I can change the background color.");
document.bgColor="#EEEEEE";
}
How to call the function
alert_box();
Function called thru an event handler
Here is a function to change the background color.
function change_back(colorval)
{
document.bgColor=colorval;
}
How to call it
Red background
Green background
Another way to describ the color
Blue background
Return
This flow of execution can be stopped by including a return statement, which causes the function to return a value, hencethe statements after returnare not executed. Its syntax is:
return expression
return $name
return false
return favorite color is blue
return 1000
The expression may be either a variable or value.
Conditional and Loops Statements
IF Else
Syntax
if (condition) {
statements to execute
}
if (condition) {
Statements to execute
}else{
Do this instead
}
if (condition) {
Statements to execute
8/3/2019 Javascript Referance - Jan Zumwalt
14/36
NeatInfo.com by Jan Zumwalt May 27, 2012JavaScript Reference Copyright 2005-2012
Pg 14 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 onall 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("...");
}
8/3/2019 Javascript Referance - Jan Zumwalt
15/36
NeatInfo.com by Jan Zumwalt May 27, 2012JavaScript Reference Copyright 2005-2012
Pg 15 of 36
For Loop
Syntax
for (initialization; condition; increment) {... statements ...
}
The increment can be any mathematical statement such as x=x-5, etc.
Print out 10 numbers
msg = "";
for (var x = 1; x
8/3/2019 Javascript Referance - Jan Zumwalt
16/36
NeatInfo.com by Jan Zumwalt May 27, 2012JavaScript Reference Copyright 2005-2012
Pg 16 of 36
Continue & Break
continue: causes the iteration to be skippedbreak: stops the entire loop and program execution starts after the loop.
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
8/3/2019 Javascript Referance - Jan Zumwalt
17/36
NeatInfo.com by Jan Zumwalt May 27, 2012JavaScript Reference Copyright 2005-2012
Pg 17 of 36
Buttons
Standard Buttons
Javascript Buttons
// 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?");
}
}
Change browser status bar
Go to a wb page
Here is a back button
Here is a forward button
An alert button
Confirm function button
Confirm var button
Prompt function input
8/3/2019 Javascript Referance - Jan Zumwalt
18/36
NeatInfo.com by Jan Zumwalt May 27, 2012JavaScript Reference Copyright 2005-2012
Pg 18 of 36
href links
anchors
Name an internal anchor
Meta Refresh Tag
link to internal or external anchor Sample text.
Mouse overTo the
Table of Contents
Mouse over & out
To the Table of
Contents
PHP button use
Standard button (GET)
print '';
Form submit (POST)
print '';
Simple Rollover Button Image (onmouseover)
8/3/2019 Javascript Referance - Jan Zumwalt
19/36
NeatInfo.com by Jan Zumwalt May 27, 2012JavaScript Reference Copyright 2005-2012
Pg 19 of 36
Advanced Rollover Button (function)
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;
}
8/3/2019 Javascript Referance - Jan Zumwalt
20/36
NeatInfo.com by Jan Zumwalt May 27, 2012JavaScript Reference Copyright 2005-2012
Pg 20 of 36
Advanced Rollover Button (alternative method)
In case of several images, it is advisable to pack the code in a function that can be called repeatedly by event
handlers using different parameters. Two variables need to be passed in the roll-over code. One is the imagename and the other is the image source.
function roll_over(img_name, img_src) {
document[img_name].src = img_src;
}
We can now call this function from our even handlers and pass it the two arguments.
List Boxes
Selection lists are quite commonly used in forms-with some help from JavaScript, it can be very usefulsometimes.
Simple List Box
choice1
The fundamental way to access forms is through its name. Accessing selection lists are no different. Here's anexample:
choice1
choice2
choice3
choice4
To access anything within this selection list, we would write:
document.box1.example
Accessing selection lists in JavaScript can be quite confusing. Where's the confusion, you ask? Well, the aboveline 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.
Accessing Elements Of The List
Using the above list as an example, with values added in for each element:
choice1
choice2
choice3
choice4
8/3/2019 Javascript Referance - Jan Zumwalt
21/36
NeatInfo.com by Jan Zumwalt May 27, 2012JavaScript Reference Copyright 2005-2012
Pg 21 of 36
JavaScript gives us access to the individualelements (choice1, choice 2, choice 3 etc) by using the optionsarray. An array is a series of variables all with the same name, but with different index numbers. (More on this inthe 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"
And to access the final element, we would do this:
document.box1.example.options[3]
//gives us access to element "choice4"
It doesn't take a rocket scientist to realize that the number inside the [ ] are always "1" minus the actual positionof 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 returns the actual text (name) of the element
value returns the value of the element
Lets say we want to alert the name of the first element (in this case, the name is "choice1"):
choice1 Show me the text!
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 indexnumber 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 automaticallyupdate itself whenever a different selection is made by the user, and see some practical uses of this.
Properties of Option Array
The keyword here is "itself". In the last page, we looked at properties of elements of the options array,
8/3/2019 Javascript Referance - Jan Zumwalt
22/36
NeatInfo.com by Jan Zumwalt May 27, 2012JavaScript Reference Copyright 2005-2012
Pg 22 of 36
NOT the options array itself.
Just to refresh our minds, here are the properties we looked at last section:
Properties of the elements of the options array
properties description
text returns the actual text (name) of the element
value returns the value of the element
We will now look at properties of the options array itself:
Properties of the options array itself
properties description
length tells us the number of elements within this selection list
selectedIndex 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
Lets see this in action:
choice1
choice1
choice2
choice3
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 exampleabove may not seem like much, but it paves the way for many useful scripts.
8/3/2019 Javascript Referance - Jan Zumwalt
23/36
NeatInfo.com by Jan Zumwalt May 27, 2012JavaScript Reference Copyright 2005-2012
Pg 23 of 36
Combo List box
A common use of the above knowledge is to create a combo link box, where the selection list acts as a urljumper. Here's an example:
Cnet.
Before we plunge right in, lets first put together all our ideas we've learned in Lesson15 and 16. Recall fromLesson 15, that to access the individual elements, we would write:
document.box1.example.options[x]
where "x" is the index number of the element.
Also recall from what we've just mentioned, that the selectedIndex property of the options array returns theindex of the element that's currently selected:
document.box1.example.options.selectedIndex
Now, with the above two pieces of code, we are all set to make our combo box script!
Cnet.
choice1
choice2
choice3
function go(){
location=document.box1.example.
options[document.box1.example.selectedIndex].value
}
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 returnsthe value of that particular element. Now, since the "red" script is a self updating script that automaticallychanges index numbers whenever a user selects another element, the "blue" script will in turn always get thevalue (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 withJavaScript and "doing your own thing."
List Box Processing
This JavaScript example sends the chosen option value to a
script to be processed.
8/3/2019 Javascript Referance - Jan Zumwalt
24/36
NeatInfo.com by Jan Zumwalt May 27, 2012JavaScript Reference Copyright 2005-2012
Pg 24 of 36
dog
cat
bird
selectmenu=document.getElementById("my_menu") // what object we are testing
selectmenu.onchange=function(){ // this code runs when "onchange" event fires
chosenoption=this.options[this.selectedIndex] // this refers to "selectmenu"
if (chosenoption.value!="nothing"){
// this code is run when a menu item is chosen
// chosenoption.value contains the data in option value
// in this example the option value is a web page
window.open(chosenoption.value, "", "") //open page based on option's value
}
}
ListBox List Popup Menu
This example uses a black box JavaScript include file located at include/pop_menu.js. When You click on alist item, a menu of options pops up for that item.
#popitmenu{
position: absolute;
background-color: white;
border:1px solid black;
font: normal 12px Verdana;
line-height: 18px;z-index: 100;
visibility: hidden;
}
#popitmenu a{
text-decoration: none;
padding-left: 6px;
color: black;
display: block;
}
#popitmenu a:hover{ /*hover background color*/
background-color: #CCFF9D;
}
/* *******************************************************
* Pop-it menu- Dynamic Drive (www.dynamicdrive.com) *
******************************************************* */
var defaultMenuWidth="150px" //set default menu width.
var linkset=new Array()
//SPECIFY MENU SETS AND THEIR LINKS. FOLLOW SYNTAX LAID OUT
// A url tag must be used, so we point to ourself and call a routine for other work to do
linkset[0]='Actions' // heading
linkset[0]+='' //Optional Separator
linkset[0]+='
8/3/2019 Javascript Referance - Jan Zumwalt
25/36
NeatInfo.com by Jan Zumwalt May 27, 2012JavaScript Reference Copyright 2005-2012
Pg 25 of 36
onClick="my_function($my_var)">View/Edit File'
linkset[0]+='Move File'
linkset[1]='Actions' // sub-heading
linkset[1]+='' //Optional Separator
linkset[1]+='JavaScript Kit'
linkset[1]+='Coding Forums'
linkset[1]+='CSS Drive'
linkset[1]+='Freewarejava'
////No need to edit beyond here
var ie5=document.all && !window.opera
var ns6=document.getElementById
if (ie5||ns6)
document.write('')
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
8/3/2019 Javascript Referance - Jan Zumwalt
26/36
NeatInfo.com by Jan Zumwalt May 27, 2012JavaScript Reference Copyright 2005-2012
Pg 26 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
The menu to use this is very simple
Webmaster Links
file2.txt
News sites
Redirection and new windows
Example 1:
8/3/2019 Javascript Referance - Jan Zumwalt
27/36
NeatInfo.com by Jan Zumwalt May 27, 2012JavaScript Reference Copyright 2005-2012
Pg 27 of 36
onclick="window.open(this.href,this.target, 'width=300, height=300, menubar=no, ststus=no')">
Example 2:
The open() takes arguments. When used without any arguments, the new window displayed is blank.
Open a new window
The open() method takes four arguments:
window.open('URL', 'NAME', 'FEATURES', 'REPLACE')
NAME: Specifies a name for the new window that can then be used as value for the TARGET attribute of tags.
FEATURES: Lets you define properties of the window such as width, height, presence or absence of scrollbars, locationbar, status baretc. 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!
List of important features
The features argument is optionaland consists of a comma separated list of features. If this argument is omittedthe new window has all features present in it. However, if at least one feature is present, the JavaScriptinterpreter will consider only the ones that appear, ignoring the features that are absent.
height: Specifies height of the window in pixels.
width: width of the new window in pixels
location: determines the presence of the location bar
menubar: menubar
scrollbars: scrollbars
status: status bar
toolbar: toolbar
directories: specifies the display of link buttons
resizable: determines whether the window can be resized. If it's absent or its value is set 'no', the windowdoes not have resize handles around its border.
fullscreen: Specific to the Internet Explorer, it determines whether the window is displayed in the full screenmode.
The width and the height take a number (pixels) as value, for other features the value is either a yesor 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 thereare no quotes surrounding the values.
Open a new window
Note: in this (and others) example the entire JavaScriptcode (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.
8/3/2019 Javascript Referance - Jan Zumwalt
28/36
NeatInfo.com by Jan Zumwalt May 27, 2012JavaScript Reference Copyright 2005-2012
Pg 28 of 36
Open a new window
Example 5:
In this example we want to specify a width and height, that forces us to include the other options.
Open a new window
Example 6:
Here is a small novelty for Internet Explorer users. The fullscreen feature can only be used with IE browsersand displays the document on the entire screen. A neat effect... sort of! Click on the F11 to remove the fullscreen display.
Open a full screen window
Example 7:
Using a function to open a new window. We name this function open_win and place it in the HTML head section.
function open_win() {
window.open('welcome.html','welcome','width=300,height=200,
menubar=yes,status=yes,location=yes, toolbar=yes,scrollbars=yes');
}
Calling the function
Get a welcome message
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 placewhere we specify the URL for the new window, however, this time it's not enclosed in quotes.To call the open_winfunction, we pass an argument which is the url address of the document we plan to displayin the new window.
open_win("welcome.html");
Creating a link to call the URL
8/3/2019 Javascript Referance - Jan Zumwalt
29/36
NeatInfo.com by Jan Zumwalt May 27, 2012JavaScript Reference Copyright 2005-2012
Pg 29 of 36
onclick="open_win('welcome.html')">Welcome message
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.
document.write('Blue denim');
Browser detection
Javascript keeps track of browser information using the navaigator object
navigator.appName - Gives the name of the browser (applicationName)
navigator.appVersion - Gives the browser version (applicationVersion)
navigator.appCodeName - Gives the browser codename (application CodeName)
navigator.platform - Gives the platform on which the browser is running
bname = navigator.appName;
if (bname == "Microsoft Internet Explorer")
{
window.location="explorer_version.html";
}
else
{
8/3/2019 Javascript Referance - Jan Zumwalt
30/36
NeatInfo.com by Jan Zumwalt May 27, 2012JavaScript Reference Copyright 2005-2012
Pg 30 of 36
window.location="netscape_version.html";
}
Date & TimeTo start working with dates and time, we first initialize a variable and assign it a value with the new operator and the Date()
constructor. The main function of the new operator with Date() constructor is to create a new date object that is stored in the
variable. Here is the code:
var d = new Date();
Thus, variable d contains a new date object. We can now call the various methods of this date object.
var t_date = d.getDate(); // Returns the day of the month
var t_mon = d.getMonth(); // Returns the month as a digit
var t_year = d.getFullYear(); // Returns 4 digit year
var t_hour = d.getHours(); // Returns hours
var t_min = d.getMinutes(); // Returns minutesvar t_sec = d.getSeconds(); // Returns seocnds
var t_mil = d.getMilliseconds; // Returns Milliseconds
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);
Check for number
var n = prompt("Enter a number", "Type your number here");
n = parseInt(n);
if (isNaN(n)) {
alert("The input cannot be parsed to a number");
}
else {
other code goes here
}
Print page
If you click this button you should be prompted with whatever application your computer uses to handle its printfunctionality.
Redirect
By setting window.locationequal to a new URL, you will change the current webpage to the one that is specified.
window.location = "http://www.test.com/"
Redirect with time delay
8/3/2019 Javascript Referance - Jan Zumwalt
31/36
NeatInfo.com by Jan Zumwalt May 27, 2012JavaScript Reference Copyright 2005-2012
Pg 31 of 36
function delayer(){window.location = "http://www.test.com"}
Prepare to be redirected!
You will be redirected in 5 sec, please update your bookmarks to our new location!
Toggle ID Visibility
ID selectors allow us to identify a unique element on the web page. Remember that a CLASS can be used manytimes. But a ID may only be used one time on a page. You write an ID selector in exactly the same way thatyou use the Class selectors. The only difference is the spelling of the word CLASS vs ID.
Hello world text
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 byreferring to its ID name.
We now present a script that allows the title of our web page to either changeits visibility (its there, we just wont see it), or to entirely remove it from, or add itto the web page.
CSS Style Example
body { font-family: arial; }
p { font-style: italic; color: #059; }
h1 { color: red; }
h2 { color: blue; font-size:12pt; }
// 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";
}
}
Nursery Rhyme
Mary Had A Little Lamb
8/3/2019 Javascript Referance - Jan Zumwalt
32/36
NeatInfo.com by Jan Zumwalt May 27, 2012JavaScript Reference Copyright 2005-2012
Pg 32 of 36
First stanza
Mary had a little lamb,
Its fleece was white as snow;
And everywhere that Mary went,
The lamb was sure to go.
Second stanza
He followed her to school one day,
Which was against the rule;
It made the children laugh and play
To see a lamb at school.
[ Toggle Visibility ]
[ Toggle Display ]
When you click on one of the links at the bottom, it causes one of the javascript routines to be run and changesthe visibility or existence of the page title that we gave a ID=toggleMe.
8/3/2019 Javascript Referance - Jan Zumwalt
33/36
NeatInfo.com by Jan Zumwalt May 27, 2012JavaScript Reference Copyright 2005-2012
Pg 33 of 36
Method & Function Reference
Methods (acts on object)ObjecttoString
toLocalString
valueOf
hasOwnProperty
isPrototypeOf
propertyIsEnumerable
String
charAt
charCodeAt
fromCharCode
concat
indexOflastIndexOf
localeCompare
match
replace
search
slice
split
substring
substr
toLowerCase
toUpperCase
toLocaleLowerCase
toLocaleUpperCaseRegex
test
match
exec
Array
concat
join
push
pop
reverse
shift
slice
sort
splice
unshift
Number
toFixed
toExponential
toPrecision
Date
parse
toDateString
toTimeString
getDate
getDay
getFullYear
getHoursgetMilliseconds
getMinutes
getMonth
getSeconds
getTime
getTimezoneOffset
getYear
setDate
setHours
setMilliseconds
setMinutes
setMonth
setSecondssetYear
toLocale TimeString
Doc Methods (DOM)Document
clear
createDocument
createDocumentFragment
createElement
createEvent
createEventObject
createRangecreateTextNode
getElementsByTagName
getElementById
write
Node
addEventListener
appendChild
attachEvent
cloneNode
createTextRange
detachEvent
dispatchEvent
fireEvent
getAttributeNS
getAttributeNode
hasChildNodes
hasAttribute
hasAttributes
insertBefore
removeChild
removeEventListener
replaceChild
scrollIntoView
Form
submitDOM Collections
item
Range
Collapse
createContextualFragment
moveEnd
moveStart
parentElement
select
setStarBefore
Style
getPropertyValue
setPropertyValueEvent
initEvent
preventDefault
stopPropegation
XML
serilizeToString
open
send
loadXML
Parser
parseFromString
WindowAlert
Blur
clearTimeout
close
focus
open
setTimeout
Built In
EvalparseInt
parseFloat
isNaN
isFinite
decodeURI
decodeURIComponent
encodeURI
encodeURIComponent
excape
unexcap
8/3/2019 Javascript Referance - Jan Zumwalt
34/36
NeatInfo.com by Jan Zumwalt May 27, 2012Copyright 2005-2012
Pg 34 of 36
Notes:
_____________________________________________________________
______________________________________________________________
______________________________________________________________
______________________________________________________________
______________________________________________________________
______________________________________________________________
______________________________________________________________
______________________________________________________________
______________________________________________________________
______________________________________________________________
______________________________________________________________
______________________________________________________________
______________________________________________________________
______________________________________________________________
______________________________________________________________
______________________________________________________________
______________________________________________________________
______________________________________________________________
______________________________________________________________
______________________________________________________________
______________________________________________________________
______________________________________________________________
______________________________________________________________
______________________________________________________________
______________________________________________________________
______________________________________________________________
8/3/2019 Javascript Referance - Jan Zumwalt
35/36
NeatInfo.com by Jan Zumwalt May 27, 2012Copyright 2005-2012
Pg 35 of 36
Notes:
_____________________________________________________________
______________________________________________________________
______________________________________________________________
______________________________________________________________
______________________________________________________________
______________________________________________________________
______________________________________________________________
______________________________________________________________
______________________________________________________________
______________________________________________________________
______________________________________________________________
______________________________________________________________
______________________________________________________________
______________________________________________________________
______________________________________________________________
______________________________________________________________
______________________________________________________________
______________________________________________________________
______________________________________________________________
______________________________________________________________
______________________________________________________________
______________________________________________________________
______________________________________________________________
______________________________________________________________
______________________________________________________________
______________________________________________________________
8/3/2019 Javascript Referance - Jan Zumwalt
36/36
Tutorials
http://www.w3schools.com/js/d
http://www.pageresource.com/j
http://www.tizag.com/javascript
References
http://www.w3schools.com/jsref
http://www.devguru.com/techno
http://www.d.umn.edu/itss/traini
Back Page
fault.asp
cript/
/
/default.asp
logies/ecmascript/quickref/javascript_index.html
ng/online/webdesign/javascript.html