Home > Notes Last Updated: 11/17/06

~ JavaScript Notes ~
(take advantage of the 'view source' option!)
(also note that you must know HTML before learning JavaScript!)


Some JaveScript Notes taken from HTML GOODIES
         

* Events

  • onMouseOver event : reacts when mouse cursor is over link/pic/etc. : placed inside A , IMG , etc. TAG
    what to expect on this example: alert box pop-up when cursor is over link

    CODE:
    <a href="index.html" onMouseOver="alert('MOUSE OVER LINK')" target="parent">LINK</a> LINK

  • onMouseOut event : reacts when mouse cursor is off link/pic/etc.
    what to expect on this example: alert box pop-up when cursor is off link

    CODE:
    <a href="index.html" onMouseOut="alert('MOUSE OFF LINK')" target="parent">LINK</a> LINK
     
  • onMouseOver / onMouseOut event (example on image flip) : image changes when mouse rolls over image

    CODE:
    <img src="pic/javas_off.jpg" onMouseOver="document.pic1.src='pic/javas_on.jpg'" onMouseOut="document.pic1.src='pic/javas_off.jpg'" name=pic1>
    OR
    <a href="index.html" target="parent" onMouseOver="document.pic2.src='pic/javas_on.jpg'" onMouseOut="document.pic2.src='pic/javas_off.jpg'">
    <img src=pic/javas_off.jpg name="pic2" width="171" height="68"> </a>

        
         (example on image)               (example w/ image as link)

  • onClick event : reacts when user click on link/pic/etc.
    what to expect on this example: alert box pop-up when click on link

    CODE:
    <a onClick="alert('CLICK')">LINK</a> LINK

  • onDblClick event : reacts when user double click on link/pick/etc.
    what to expect on this example: alert box pop-up when click on link

    CODE:
    <a onDblClick="alert('CLICK CLICK')">LINK</a> LINK

  • onFocus / onBlur event : reacts when focusing / un-focusing on link/pic/etc.; focusing occurs when the dotted box is on the object

  • onChange event : reacts when something changes
    what to expect on this example: alter textbox, un-focus textbox and alert box will pop-up

    CODE:
    <form><input type="text" value="alter this if you dare!" size="20" onChange="alert('You changed it!')"></form>
  • onSubmit event : reacts when submitting via forms

    CODE:
    <form><input type="submit" onSubmit="alert('SUBMITTED!!!')"></form>
  • onLoad / onUnload event : reacts when entering/exiting website
    what to expect on this example: alert box pop-up when entering/exiting website

    CODE:
    <body onLoad="alert('Welcome, this is the onLoad event!\r\rEnjoy your stay!')" onUnload="alert('Bye!!, this is the onUnload event!\r\rThank you and Come Again! (in Apu\'s accent)')">
    (event already executed upon entering/exiting this page)

  • onMouseDown / onMouseUp event : reacts when mouse click down and up
    what to expect on this example: look at status bar

    CODE:
    <span onMouseDown="window.status='MOUSE IS DOWN'" onMouseUp="window.status='MOUSE IS UP'" onMouseOut="window.status=' '">LINK</span>
    LINK

  • onKeyPress event : reacts when keyboard key is pressed
     
  • onKeyDown / onKeyUp event : reacts when keyboard goes down


* Special HTML Tags

SPAN tag : used to create javascript on the fly
LINK

<SCRIPT LANGUAGE="javascript">Everything between this is JavaScript stuff </SCRIPT>


* Objects and their Methods & Properties

history object
.go method

CODE:
<form>
<input type=button value=back onClick="history.go(-1)">
<input type=button value=forward onClick="history.go(1)">
</form>

Date object
.getDate() method : returns the day of the month as correctly numbered day of the month from 1 to 31 (Good2Go)
.getDay() : returns the numbers 0 (sunday) through 6 (saturday), depending on the day of the week
.getHours() : returns the hour of the day in a 24-hour format counting the hours up from 0 to 23 (G2G)
.getMinutes() : returns the minute of the hours counting up from 0 up through 59 (G2G)
.getMonth() : returns the month of the year counting up from 0 (january) to 11 (december)
.getSeconds() : returns the second of the minute counting up from 0 to 59 (G2G)
.getFullYear() : returns the 4-digit year (G2G)

document object
.write() method : : alinkColor, bgColor, fgColor, linkColor, lastModified, location, referrer, title, vlinkColor

history object
.go() method : : length

location object : host, hostname, href

Math object
.random()
.round()
...there's a big list of methods related to this object....WILL LIST LATER

navigator object : appCodeName, appName, appVersion, userAgent

self object
.close() method

window object
.close() method : : defaultstatus, directories, location, menubar, resizable, self, scrollbars, status, toolbar


* Commands

  • alert('message') - creates a pop-up alert box with message and OK button

    CODE:
    <span onClick="alert('Here\'s the ALERT command!')"><br>
    <u>CLICK HERE</u></span>


    CLICK HERE

  • confirm('message') - creates a pop-up alert box with messag and OK & CANCEL buttons
    (NOTE: javascript is involved in creating conditional statements(if / else) for OK and CANCEL buttons)


    CODE:
    <script language="javascript">
    function confirmBox() {
    if (confirm("Click OK if you want a WOOHOO message\rClick CANCEL if you want a NOOOO! message.")) alert("WOOHOO!");
    else alert("NOOOO!");
    }
    </script>
    <span onClick="confirmBox()"><u>CLICK HERE</u></span>


    CLICK HERE

  • prompt('message', 'reply') - creates a pop-up prompt box with message and a reply for user to input

    CODE:
    <span onClick="prompt('Here\'s the PROMPT command', 'Default reply message')"><br>
    <u>CLICK HERE</u></span>


    CLICK HERE
  • window.status('text') - status bar will display this text

    CODE:
    <span onClick="window.status='Here\'s the status command'"><br>
    <u>CLICK HERE<br></u></span>


    CLICK HERE
  • window.defaultstatus ('text')

Note that when embedding JavaScript onto HTML, you use the window.status('text'), but when you're writing code between JavaScript TAGS, it's status= text (or defaultstatus = text)


* Special Examples of JavaScript
Example 1: Prompt user for name and then place message w/ name on website.
CLICK HERE

Example 2: EMPTY
CLICK HERE


* NOTES *

* Escape Characters

When you use wish to use quotations in JavaScript in your text, you must have the \ symbol or you'll get an error!

\"
\'
\r  - creates a carriage return

- variables:
var variablename = (things);

- arrays:
var arrayname = new Array("text1", "text2", "text3", "text4");

then if you were to enter " arrayname[0] ", that would output text11

- conditional statement (?:)
assigns a variable name depending on the results

eg. YearsInCompany = (ywc >=45) ? "retire" : "noretire";

if ywc >=45, then YearsInCompany = "retire", else YearsInCompany = "noretire"

- preloading images: this will store these images into your browser cache on your hd (placed between head tags)
<script language="javascript">
Img01 = new Image(w, h);
Img01.src = "location of image";
</script>

- opening new windows (pop-up window on loading):
<script language="javascript">
window.open('opened.html','nameofwindow','config='height=300,width=300')
</script>

<a href="http://www.oocities.org target="nameofwindow">text</a>

(note: config command has these options; you would answer YES or NO for each:
-toolbar=   The line of buttonns at the top of the browser window
-menubar=   The line of items labeled File, Edit, View, ...
-scrollbars=   Scrollbars....<
-resizable=   Denotes whether user can change size of window by dragging.
-location=   The URL address bbar at the top of browser.
-directories=   Bar at top of Netscape browser
-status=   Denotes whether thee window will have a status bar.

- opening new windows (pop-up window on command; html page pre-created):
CODE:
<script language="javascript">
function openIt() {
  window.open('somewhere.html','nameofpopup',config='height=300,weight=300');
}
</script>


<a href="javascript:onClick=openIt()">Click to open Popup</a>
OR
<span onClick="openIt()">CLICK HERE</span> CLICK HERE

- opening new windows (pop-up window; html page created on the fly):

CODE:
<script language="javascript">
function openThis() {
var OpenWindow=window.open("", "newwin","height=300,width=300");
  OpenWindow.document.write("<HTML>");
  OpenWindow.document.write("<TITLE>New Window</TITLE>");
  OpenWindow.document.write("<BODY BGCOLOR='00ffff'><CENTER>");
  OpenWindow.document.write("<FONT SIZE=+1> New Window </FONT>");
  OpenWindow.document.write("insert more and more and more html as you would on a regular page");
  OpenWindow.document.write("</CENTER></HTML>");
}
</script>

<body onLoad="openThis()"></body>

OR

<a href="somewhere.html" onClick="openThis()">

- closing a window:
<a href="" onClick="self.close()">CLICK 2 CLOSE</a>

OR

<form>
<input type=button value="CLICK 2 CLOSE" onClick="self.close()">
</form>

- data detection in textbox (example1):

CODE:
<script language="javascript"> function readIt() { alert("You wrote " + document.myform.thebox.value + " in the box."); } </script> <form name="myform">
Write something here---><input type="text" name="thebox" value=""> <input type="button" value="CLICK HERE AFTER" onClick="readIt()">
</form>
Write something here--->

- data detection in textbox, advanced (example2):

CODE:
<script language="JavaScript">
function readIt2() {
var greeting = "Hello ";
alert(greeting + document.myform2.fname.value + " " + document.myform2.lname.value);
alert("lenght of first name" + document.myform2.fname.value.length);
alert("First name in ALL CAPS: " + document.myform2.fname.value.toUpperCase());
alert("Full name in al lowercase letters: " + document.myform2.fname.value.toLowerCase() + " " + document.myform2.lname.value.toLowerCase());
document.myform2.receiver.value= ("Thanks " + document.myform2.fname.value + ".");
}
</script>
<form name="myform2">
What's your first name<input type="text" name="fname"><br>
What's your last name<input type="text" name="lname"><br>
<input type="button" value="Submit" onClick="readIt2()"><br>
Look here after Alert Boxes: <input type="text" name="receiver">
</form>
What's your first name
What's your last name

Look here after Alert Boxes:

- user setting bg color:

CODE:
<script language="JavaScript">
function newColor(color) {
alert("You chose " + color);
document.bgColor=color;
}
</script>
<form>
SELECT THE BACKGROUND COLOR TO CHANGE:&nbsp;
<input type="button" value="blue" onClick="newColor('blue')">&nbsp;
<input type="button" value="black" onClick="newColor('black')">&nbsp;
<input type="button" value="white" onClick="newColor('white')">
</form>
<
SELECT THE BACKGROUND COLOR TO CHANGE:     

- cool way to append stuff:

CODE:
<script language="JavaScript">
function goFind() {
var searchfor = document.formsearch.findthis.value;
var fullsearchurl = "http://www.google.com/search?hl=en&ie=UTF-8&oe=UTF-8&q=" + searchfor;
location.href = fullsearchurl; //this line immediately goes to that site
}
</script>

<form name="formsearch">
Search Yahoo for: <input name="findthis" size="40" type="text"> <input type="button" value="GO FIND NOW" onClick="goFind()">
</form>
Search Google for:
- pull-down menus of links:

CODE:
<script language="JavaScript">
function linkUp() {
var number = document.dropdown.ddlinks.selectedIndex;
location.href = document.dropdown.ddlinks.options[number].value;
}
</script>

<form name="dropdown">
<select name="ddlinks">
<option selected value="index.html">Choose Your Link</option>
<option value="java.html">Java Page</option>
<option value="c.html">C Page</option>
<option value="javas.html">JavaScript Page</option>
<option value="mylinks.html">myLinks Page</option>
</select>
<input type="button" value="CLICK HERE" onClick="linkUp()">
</form>

- guestbook via javascript:

CODE:
<script language="JavaScript">
var name = prompt("What's your first name?","Write It Here");
var email = prompt("What's your e-mail address?","Write It Here"); function verify() {
var OpenWindow = window.open("", "newwin","height=300, width=300");
OpenWindow.document.write("<html><title>Thanks for Writing</title>");
OpenWindow.document.write("<body bgcolor='ffffcc'><center>");
OpenWindow.document.write("Thanks you <b>" + name + "</b> from <b> " + email + "</b><p>");
OpenWindow.document.write("Your message <p><i>" + document.gbookForm.maintext.value + "<i><p>");
OpenWindow.document.write("from " + name + " / " + email + "<p>");
OpenWindow.document.write("will be sent along when u close this window.<p>");
OpenWindow.document.write("<form><input type='button' value='Close Window' onClick='self.close()'></form>");
OpenWindow.document.write("</center></body></html>");
}
document.write("<form method='post' action='mailto:jhl07@hotmail.com?Subject=Mail from " + name + " at " + email + "' enctype='text/plain' name='gbookForm'>"); </script>

<b>tell me something now!</b><br>
<textarea cols="40" rows="10" name="maintext"></textarea>
<p><input type="submit" value="Send It" onClick="verify()"></form></p>

tell me something now!

- math, math, and more math:

CODE:
<script language="JavaScript">
function figureOut() {
var dinCost = document.meal.dinner.value
var tipCost = dinCost * .15;
var bigtipCost = dinCost * .25;
document.meal.tip.value = tipCost; //the reason why it's flipped backwards is becuase you're showing the tipcost on the text-box
document.meal.bigtip.value = bigtipCost;
}
</script>

<form name="meal">
How much was dinner? $<input type="text" name="dinner">&nbsp;<input type="button" value="Calculate" onClick="figureOut()"><p>
You should tip: $<input type="text" name="tip"><br>
Big tiiper would leave: $<input type="text" name="bigtip">
</form>

How much was dinner? $ 

You should tip: $
Big tiiper would leave: $

- random numbers:

CODE:
<script language="JavaScript">
function rand() {
var now = new Date();
var num = (now.getSeconds())%9;
var numEnd = num + 1;
alert(numEnd);
}
</script>

<form>
<input type="button" onClick="rand()" value="Random # from 1 to 10">
</form>

CODE:
<script language="javascript">
var num = Math.round(35 * Math.random());
document.write("Random number from 0 to 35 : <b>" + num + "</b>.");
</script>

(For more information on the Math class and its objects, view the above 'Objects and Methods' section)

- more useful ways of using random #s (producing random statements and images)

CODE:
<script language="javascript">
function randStatement() {
var var0 = "An Apple A Day";
var var1 = "A Stitch in Time";
var var2 = "Bird in the Hand";
var var3 = "Super duper Superman";
var var4 = "Go go gadget ARMS!";
var num = Math.round(5 * Math.random());
if (num == 0) cliche = var0;
if (num == 1) cliche = var1;
if (num == 2) cliche = var2;
if (num == 3) cliche = var3;
if (num == 4) cliche = var4;
alert(cliche + " as I always say");
}
</script>

<form><input type="button" value="Generate random statement" onClick="randStatement()"></form>

(to generate random images, simply change the var# = "image.jpg")

- introduction to for loops:

CODE:
<script language="JavaScript">
for (i=1; i<=5; i++) {
document.write(i + "<br>");
}

</script>

Count from one to five...
...and we're done.

- while loops:

CODE:
<script language="JavaScript">
loops = 5;
while (loops >= 1) {
document.write("HAPPY ");
loops--;
}
document.write("BIRTHDAY!");

</script>

- browser detection script :

CODE:
<script language="JavaScript">
if (navigator.appName == "Netscape") document.write("YOU ARE USING NETSCAPE BABY!");
else if (navigator.appName == "Microsoft Internet Explorer") document.write("YOU ARE USING IE BABY!");
else document.write("WHAT THE HELL ARE YOU USING??");
</script>

- a running clock:

CODE:
<script language="JavaScript">
function RunningTime() {
var NOW = new Date();
var hour = NOW.getHours() + 1;
var minute = NOW.getMinutes();
var second = NOW.getSeconds(); var printIt = "Time: " + hour + ":" + minute + ":" + second; document.clock.clockFace.value = printIt; //sticks whatever printIt is into this textbox
setTimeout("RunningTime()","1000");
}
</script>
<body onLoad="RunningTime()">

<form name="clock">
<input type="text" name="clockFace">
</form>

- countdown timer:

CODE:
<script language="javascript">
mil = new Date("January 1, 2005");
mil.setYear = now.getFullYear;
day = 1000*60*60*24;
computeDay = (mil.getTime() - now.getTime()) / day;
DayResult = Math.round(computeDay);
document.write(DayResult + " days until January 1<sup>st</sup>, 2005");
</script>

- scrolling text:

CODE:
<script language="javascript">
var space = " ";
var scr = space + "This text is scrolling along...";

function Scroll() {
var temp = scr.substring(0,1);
scr += temp;
scr = scr.substring(1, scr.length);
document.Scroll.ScrollBox.value = scr.substring(0,55);
setTimeout("Scroll()", 50);
}

</script>
<body onLoad="Scroll()"> <form name="Scroll">
<input type="text" size="50" name="ScrollBox" value="">

Home | Profile | Notes | Space | Links