Following is a collection of reference material on javascript. The sources are from the web.
Properties | Methods |
bgColor (changes bgcolor) |
write (writes something, see below) |
lastModified (gives date of document's last change) |
writeln (writes in new line) |
referrer (gives URL of the page that linked here) |
|
fgColor (changes foreground color (text)) |
document.write() -- writes in current document. e.g.:
var current= new Date() var day_night=current.getHours() if (day_night<=12) document.write("<img src='day.gif'>") else document.write("<img src='night.gif'>")
Properties | Methods |
location(sets the current page URL) | alert (pops up a msg box with given msg) |
closed | confirm (pops up a msg box asking to confirm with given msg) |
defaultStatus | prompt (pops up a msg box asking input with given msg, returns input) |
document | open (opens a separate browser window) |
Frame | blur |
frames | clearTimeOut |
history | close |
length | focus |
name | setTimeOut |
opener | |
parent |
where attributes can be any of:
example:
<form> <input type="button" value="Click here"> onclick="window.open('page.html', 'win1','width=200,height=200,menubar')"> </form>
Remember:
Handler | Description | Use with |
onAbort | images | |
onBlur | executes whenever a user moves the focus away with the mouse from one element to another within a form. Used for entry verification. | windows, forms, frames |
onClick | invokes JavaScript upon clicking links or forms | buttons, checkboxes, radio, submit and reset buttons, links |
onChange | text fields, text areas, select lists | |
onError | windows, images | |
onFocus | windows, frames, forms | |
onLoad | invokes JS after page or image has finished loading | body, images |
onMouseover | invokes JS when mouse enters | areas, links |
onMouseout | invokes JS when mouse leaves | links |
onReset | forms | |
onSelect | text fields, text areas | |
onSubmit | executes whenever someone clicks the "submit" button | submit button |
onUnload | invokes JS after someone leaves the page | body |
Methods | Description |
getDate() | returns day of the month |
getDay() | returns day of the week |
getHours() | returns hour (0-23) |
getMinutes() | returns minutes |
getSeconds() | returns seconds |
getMonth() | returns month (0-11) |
getYear() | returns year |
getTime() | returns complete time |
getTimezoneOffset() | |
parse | |
setDate | |
setHours | |
setMinutes | |
setMonth | |
setSeconds | |
setTime | |
setYear | |
toGMTString | |
toLocaleString | |
toString | |
UTC | |
valueOf |
Solution to Y2K problem:
var year=mydate.getYear() //Y2K bug fix if (year < 1000) year+=1900
Properties | Methods |
status (sets the status line content) |
Properties | Methods |
appName (name of the browser) |
|
appversion (version, platform, and country) |
Properties | Description |
length | Number of characters in the string |
Methods | Description |
anchor(name) | puts <A NAME="name"> |
big() | puts <BIG> |
blink() | puts <BLINK> |
bold() | puts <B> |
fixed() | puts <TT> |
fontcolor(color) | puts <FONT COLOR="color> |
fontsize(size) | puts <FONT SIZE="size">. "size" ranges from 1 to 7, or relative with "+" and "-". |
italics() | puts <I> |
link(url) | puts <A HREF="url"> |
small() | puts <SMALL> |
strike() | <STRIKE> |
sub() | puts <SUB> |
sup() | <SUP> |
toLowerCase() | converts to lowercase |
toUpperCase() | converts to uppercase |
charAt(i) | returns character at position i |
concat(s1,s2,...) | combines s1, s2, ... strings into the existing |
indexOf(char/substring) | returns index of char or substring |
lastIndexOf(char/substring) | searches backwards |
slice(start,end) | returns the portion of string within the specified indices |
split(delimiter) | splits using the delimiter |
substring(from,to) | returns the substring |
example: wavy output.
var message = "Hello!" var changed = message.toUpperCase() var size = 1 //CHANGE LETTER BY LETTER for (i=0; i<message.length ;i++) { document.write(changed.charAt(i).fontsize(size).bold()) if (size<7) size++ else size=1 }
example: count words
<form name="wc"> <textarea rows="10" name="wc2" cols="25" wrap="virtual"></textarea><br> <input type="button" value="Count Words" onClick="countwords()"> <input type="text" name="wc3" size="20"> </form> <script language="JavaScript"> function countwords() { var inside = document.wc.wc2.value inside = inside.split(" ") document.wc.wc3.value = inside.length } </script>
Properties | Methods |
src | onLoad |
height, width | onError |
lowsrc | onAbort |
border | |
vspace, hspace |
example:
<head> <script> <!-- image01= new Image(42,42) image01.src="1.gif" image02= new Image(42,42) image02.src="3.gif" //--> </script> </head>
example:
// preload images <head> <script> main_image = new Image(102,45) main_image.src = "main.gif" main_image_on = new Image(102,45) main_image_on.src = "main_on.gif" </script> </head> <A HREF="main.html" onMouseover="if (document.images) document.images.main.src=main_image_on.src" onMouseout="if (document.images) document.images.main.src=main_image.src" TARGET="main_page"> <IMG SRC="main.gif" NAME="main"> </A>
example:
<html> <head> <script language="JavaScript1.1"> <!-- var image1 =new Image() image1.src="first.gif" var image2 =new Image() image2.src="second.gif" var image3 =new Image() image3.src="third.gif" //--> </script> </head> <body> <img src="first.gif" name="slide" width=100 height=52> <script> <!-- // counter var step=1 function newpic() { //check for browser support of the image object if (!document.images) return document.images.slide.src=eval("image"+step+".src") if (step<3) step++ else step=1 //automatic refresh every 3 seconds setTimeout("newpic()",3000) } newpic() //--> </script> </body> </html>
The images in the above example can be made to point to separate URL's each one by surrounding the IMG by an <A HREF="javascript:imagelink()"... where the a new extra function "imagelink()" will point to a page provided the variable step is checked.
example:
... <a href="javascript:imagelink()"><img src="first.gif" name="slide" width=100 height=52></a> ... newpic() function imagelink() { if (step==1) window.location="link1.html" else if (step==2) window.location="link2.htmll" else if (step==3) window.location="link3.html" } //--> ...
Types | Function | Example |
http: | jump to specified address | <a href="http://hereitis.com/ha.html">Click</a> |
mailto: | opens up default mail program | <a href="mailto:ccruz@bu.edu">Mail me</a> |
javascript: | executes js code | <a href="JavaScript:window.location.reload()">Reload</a> |
view-source: | views source of specified document | <a href="view-source:-complete path-">Source</a> |
about: | show info about browser, etc | <a href="about:" OR "about:cache" OR "about:plugins" ... |
No parameter function:
function test() { }
Parameter and return function:
function test(x,y) { var temp=x+y alert("you have summed parameters") return temp } test(3,5)
if statement
var x = window.confirm("Are you sure?") if (x) window.alert("yes!") else window.alert("no!?")
for statement
for (y=0;y<=5;y++) { window.alert ("hi!") } NOTE: can do "y=y+2" as other types of increment.
Arrays
var x = new Array(50) x[0] = "hey" ... x[49] = "last element"
Can access functions of one frame from another by using the parent.framename object. Example:
On the master page:
<html> <frameset cols="30%,70%"> <frame src="page1.html" name="frame1"> <frame src="page2.html" name="frame2"> </frameset> </html>
Page 1:
//page1.html <html> <body> <script> function testing() { var x="this is page1" alert(x) } </script> </body> </html>
Access function on page 1 from page 2:
//page2.html <html> <body> <script> parent.frame1.testing() </script> </body> </html>
To load multiple frames by a single click can always invoke a function such as:
<script> function loadframes() { parent.frame1.location='one.html' parent.frame2.location='two.html' parent.frame3.location='three.html' parent.frame4.location='four.html' parent.frame5.location='five.html' } </script>
where the example contains five frames that get loaded at once, either by an onclick() or by calling directly loadframes otherwise.
Remember, forms are not within the < script></script> brackets.
<form> <input type="button" name="test" value="click me" onclick="dosomething()"> </form>
<form name="hey"> <input type="checkbox" name="col1" onclick="document.bgColor='lightblue'"> <input type="checkbox" name="col2" onclick="document.bgColor='lightyellow'"> <input type="checkbox" name="col3" onclick="document.bgColor='lightgree'"> </form>
<form name='text'> <input type="text" size="10" name="output" onBlur="doinputcheck()"> <input type="reset" name="resetbutton" value="Reset"> <textarea name="thetextarea" rows="10" cols="30">Init value</textarea> <input type="submit" name="button1" value="Submit"> </form>
<form name="thechoices"> <select name="exampleChoice" size="1"> <option value="1">mychoice1</option> <option value="2">mychoice2</option> </select> </form> where the label can be accessed by: document.thechoices.exampleChoice.options[0].text the value is accessed by: document.thechoices.exampleChoice.options[0].value the number of choices is given by: document.thechoices.exampleChoice.options.length the selected options is given by: document.thechoices.exampleChoice.options.selectedIndex Note: can add a onChange="jsfunc()" as another tag inside the select description such that 'jsfunc' would be executed upon change of the option.examples:
Popup box that indicates the value of a previous input text:
<form name="thebut"> <input type="text" size="10" value="Some Init Value" name="inpbox"> </form> <input type="button" value="Click Here->" onclick="alert(document.thebut.inpbox.value)">>
Calculator:
<form name="calcexample"> <input type="text" size="20" name="calculator"> <input type="button" name="CalcButton" value="Calculate" onclick="calc()"> <input type="reset" name="ResetButton" value="Reset"> Answer:<input type="text" size="20" name="result"> </form> <script> function calc() { document.calcexample.result.value= eval(document.calcexample.calculator.value) } </script>
Change value of one widget using onMouseOver:
<form name="myform"> <textarea name="mytextarea" rows="6" cols="27">Init text</textarea> </form> <a href="whateverlink.html" onMouseover="document.myform.mytextarea.value='Showing sample\n text output.'" onMouseout="document.myform.mytextarea.value=''">Whatever Link </a>
"On submit" form:
<script> <!-- function checkValues() { // FUNCTION TO CHECK THAT THE REQUIRED FIELDS // ARE FILLED IN if ( (document.example.name.value=="")|| (document.example.feedback.value=="") ) { alert ("Please fill in the required fields.") return false } } //--> lt;/script> <form name="example" onsubmit="return checkValues()"> <Name> <input type="text" size="20" name="name"> <b>Feedback please: (*required)</b> <textarea name="feedback" rows="5" cols="20"<>/textarea> <b>Home address (*NOT required)</b> <input type="text" size="30" name="address"> <input type="submit" name="button1" value="Submit"> </form>
Combo box:
Use a choice with values pointing to URL's and do a function that executes from a button that sets the "location" to the value of the choice by: location=document.thechoices.example.options[document.thechoices.example.selectedIndex].value Note that the "location" can be one from a given frame using the "parent" construction.
Schedule a task with a delay in milliseconds.
setTimeout("expression", delaytime)
Generate a random number between 0 and 10.
var randomnumber=Math.floor(Math.random()*11)
External libraries can be created in a file with extension '.js' and called within a page by
<script src="displaydate.js"> </script>
The path can be also from somewhere else:
<script src="http://www.yahoo.com/displaynews.js"> </script>