Basic javascript


During it's "browser war" with MicroSoft's Internet Explorer, Netscape developed livescript -- a language similar to fortran/basic/C/... to write simple computer programs as part of a web page. They could be run by anyone's Netscape browser. Microsoft introduced their version of javascript, named jscript, which, of course, ran on Internet Explorer. Web page designers were thrilled, since this meant sites paid them to design two versions of each webpage (to this day, you can viewing the source for commercial websites and see tests for IE or NS.) After Java (developed by SUN) became popular for web programming, livescript was renamed javascript to cash in.

The fight ended after Microsoft drove Netscape nearly out-of-business (through monopoly abuse, which lost them the 1998 US vs MS antitrust suit.) A javascript/jscript hybred has since been standardized by the European Computer Manufacturer's Association (EMCA) as ECMAscript, but most people still call it javascript. I'll use all four terms interchangably.

Modern books on javascript that I've seen don't have much about using it with HTML until near the end. The reason for this is that javascript has since added a whole bunch of stuff to make it into a "real" programming language. In my opinion, that's a bit like selling a kit to turn a skateboard into a car, then printing books on "skateboarding" that are really Driver's Ed manuals, with a chapter on skakeboarding in the back. The only reason to use JavaScript is for web pages.

The Document Object Model (the DOM, on the w3c web site) is a w3c standard for how any programming language should interact with *ML (HTML, XML, ...) documents. It can be a bit difficult to read, but if you want to know if and how jscript can do X to a web page, look it up in the DOM, then the jscript implementation of the DOM. For an example, document.forms[0].elements[2].value="Press Me"; might change the text of the third button to "Press Me". The DOM says a web page document has a list of forms, that each form has a list of elements, each with a value. javascript decided to use the dots and to start numbering at 0.

There are several attributes, which I will completely ignore, telling the browser that your programs are in jscript, version xx.yy, and so on. If you go on to write jscript professionally, you should look these up and put them in your web pages. Whenever Firefox, IE4.0 or NS7.0 sees program-like stuff, they assume it's jscript, if you don't say.

Running javascript


There are several ways to use javascript in an HTML document. The most useful and obvious is as an event handler. Your web browser sits around waiting for you to do things -- type, move the mouse or click it. These are events. When the mouse goes over a hyperlink, a mouseover event is generated for it. The default handling is to turn the mouse picture into a little finger, but you can say you want to "handle" that event some more, and write as much javascript code as you want to do it.

When the mouse go over a paragraph, heading, bold text... it generates a same mouseover event for that, as well. These have no default behavior, but javascript will let you respond to going over any of those, if you write the code for it.


The code for an event is written as an attrubute/value pair in the opening tag. For example, this will make the background in the b-tag turn purple when it is clicked: the b-tag <b onclick="style.background='#A000FF'">turn purple</B> when...

onclick is a javascript keyword. This essentially means "on a click, run the javascript command style.background='#A000FF' (which is the javascript way of writing style="background:#A000FF". Like any other atribute/value pairs, it may be mixed with others, in any order. javascript prefers double-quotes, but, obviously, quotes in quotes will confuse the browser, so a special rule is that you may use single-quotes here (the other alternative is to escape it html-style, with &quot;. Which would look like:
<b onclick="style.background=&quot;#A000FF&quot">turn purple</B>

This emphasized text has a style attribute and an event:

<em style="text-decoration:overline" onclick="style.textDecoration='underline'">emphasized text</em>

Note how text-decoration was changed to textDecoration when used in javascript. The general rule is that stylesheet keywords used by javascript have all dashes removed and the next letter capitalized (border-top-color would be written in javascript as borderTopColor. The reason for this is dash(-) means subtract in javascript.

As usual, the span tag may be used for text which normally needs no tag (click on 'text'):

<span onclick="style.fontWeight='bold'">text</span>


These may be used by themselves, but since the changes they make are permanent, they are best used together. This will turn green when the mouse goes over and this turns yellow when the mouse leaves. This combines a mouse over/out:

...turn <b onmouseover="style.color='green'">green</b> when...
...turns <b onmouseout="style.color='yellow'">yellow</b> when...
This <b onmouseover="style.color='white'" onmouseout="style.color='black'">combines</b> a mouse...

To make something behave like a link (change color, text on bottom), do this:

<b onmouseover="window.status='look, Im down here'; style.color='red'"
   onmouseout="style.color='black'; window.status=' '">this</b>:</P>

Changing the status bar is normally disabled in firefox (spammer protection?) To enable it, select Edit->preferences->WebFeatures->advanced.

The Document Object Model says the bottom of a browser is the status part of the window, which jscript writes as window.status. javascript uses a semi-colon between statements on the same line (like bash.) The space in the final window.status=' ' seems to be required (instead of two single quotes with no space: ''.)

To do the same thing for a hyperlink, you have to tell the browser not to write the link name on the bottom. Otherwise, the browser will overwrite what you put there. You do that by saying return true (true, in this case, meaning "yes, I took care of it." If you want the link name at the bottom, use return false). This link goes nowhere:

<a onmouseover="style.letterSpacing='2px'; window.status='dont click on me'; return true;"
   onmouseout="style.letterSpacing='0px'; window.status=' '"


With form controls, you don't as much care when someone clicks, mouse over or mouses out, as you care when someone changes them. The event for that is onchange. For example, if you want a pulldown menu to change the background color:

<form><select onchange=";">
  <option value="green">green</option>
  <option value="red">red</option>
  <option value="lime">yuck</option>
  <option value="white">white</option>

Or a textbox to let you type things at the bottom: :

<input type="text" onchange="window.status=value">

value is the usual attribute of the pulldown menu, and is set the usual way. In the onchange, javascript is allowed to read and use it.

Inline (during load) commands

Javascript lines may also be run once, when the page is loaded. To do this, put <script> tags around the code and write it as normal (except you may now use double-quotes instead of single quotes.) This will put "page loading" on the status bar and display a message about the time of day (Date is explained later.)

window.status="page loading"
d=new Date()
 { document.write("<h1>Good morning</h1>"); }
else if(d.getHours()<18)
 { document.write("<h1>Good afternoon</h1>"); }
 { document.write("<h1>Good evening</h1>"); }

This can be combined with other tricks to do useful things (doing something different depending on the date, starting a delayed command, poping up an ad in a new window,... .)

Things you can do

With a C++ program in the first 1/2 of Com Sci 227, you can compute sorts of things, but all you can do with it is write it to the screen. With a shell script, you can change files and directories and also print things on the screen. jscript has variables, ifs and loops for computing things, but once you compute it, what can you do with it?

An alert box

To pop up a little window with a message, use the built-in alert() function. It is mostly useful for testing your code (displaying variable values, etc...): : <input type="button" onclick="alert('button 1 pressed')">

Changing your style rules

Use"new-value"; to change your style. For example <tt onmouseover="style.fontSize='18pt'">

Recall that would normally be written {font-size:18pt}. The new value must be in quotes, even if it looks like a number (this is the same rule for html attribute/value pair.) One small problem is that a dash in jscript is a minus sign. font-size will be interpreted as "font minus size". To get around this, style rules with dashes are changed. Remove the dash and capitalize the next letter. border-left-style would be written borderLeftStyle in javascript.

To be absolutely correct, the keyword this may be used to mean "myself", as in

Changing the top/bottom

As shown earlier, change the bottom with window.status="new value". You need to add return true when it would normally change the bottom, like for a link, but not for <onmouseover="window.status='rolled over'">

To change the title, use document.title:

<b onmouseover="document.title='title change test'">change</b>

Changing things in forms:

Forms in a document are numbered, starting from 0. You may look up the first form with document.forms[0]. Controls in a form (INPUT, TEXTAREA, SELECT) are also numbered, starting from 0. You may look at the first "control" in the first form with document.forms[0].elements[0]. You may also use the name of that element, if it has one.

Once you get there, you may directly change the style, value or selected attributes:

Make ZZZ Add y red

<form> <input type="text">
 <span onmouseover="document.forms[1].elements[0].value='ZZZ'">Make ZZZ</span>
 <span onmouseover="document.forms[1].elements[0].value=document.forms[1].elements[0].value+'y';">Add y</span>
 <span onmouseover="document.forms[1].elements[0].style.background='red'"

value is treated as a string. We can read it or change it. Unlike bash, jscript uses + to add strings (as a handy way to remember, almost everything in jscript is a copy of C++/Java.)

As a shortcut, you may often leave out document. This works if you are already in the document. Later, when we move these outside and into functions, it's important to remember document. should be there.

Another shortcut is using names. If the form or element has a name attribute, you may use that instead of forms[#]. The same example, using those shortcuts:

Make QQQQ Add y aqua

<form name="demo4"> <input type="text" name="changeMe">
   <span onmouseover="demo4.changeMe.value='QQQQ'">Make QQQQ</span>
   <span onmouseover="demo4.changeMe.value=changeMe.value+'y';">Add y</span>
   <span onmouseover="'aqua'"

If you are the form, you may use value directly (or may use this in front: <input type="text" onclick="value=' '">

Writing HTML

This "in-line" javascript will add a "Ways of the Marmots" heading (yes, it would be easier to write it without the javascipt): <script>document.write("<H1>Ways of the Marmots<H1>")<script>. Using document.write in an event is pointless -- the document has been completely read; writing more at that point just ocnfuses the browser. It is possible to insert/delete items from the page in an event, but that requires navigating the document tree and something like insertBefore or removeChild (see the w3c DOM for more.)

document.write("<H1>Ways of the Marmots<H1>");
// -->

The HTML comments are to hide it from browsers that don't know javascript, and the // comment is to hide the end --> from javascript.

<input type="button" onclick="document.write('XYZ');"> replaced the page with XYZ when I tried it.



Writing anything more than a tiny javascript program as part of a tag can be unpleasant and makes the page hard to read later. javascript copies from many other programming langauges the ability to move the program somewhere else, in a function. For anyone who's used C++/java, this is stolen directly, but see the section on variables and types.

Suppose I want several places where a mouseover writes a message to the status bar and to a text input box cheese or fruit:

function showMessage(m)
 { window.status=m

function clrMessage()
 { showMessage(" ") }
<b onmouseover="showMessage('cheese')" onmouseout="showMessage(' ')">cheese</b> or
<b onmouseover="showMessage('fruit')" onmouseout="clrMessage()">fruit</b>:</P>

Using a function from an event is similar to using an Excel spreadsheet function -- the function name with parens around the inputs; inputs separated by commas if more than one. If there are no inputs, use ().

Function are usually written in the head of the page, but may be written elsewhere. The required part is script tags and function functionName(inputs) {lines}. Any number of functions may be between the script tags. Pick any function name you like. Unlike bash, where inputs are always labelled $1, $2, ..., in javascript you must pick the names for inputs. In the example above m could be "cheese" or "fruit" or " ", depending on which event is currently using (technical term: calling) it. Also unlike bash, the event using the function must give the exact number of inputs the function is expecting.

clrMessage isn't really needed here -- I just wanted an example of multiple functions and a 0-input function. clrMessage also could have been written: window.status=" "; document.f1.messageHere.value=" ".

A function with more than one input: big medium

function goNuts(m1,m2)
 { window.status="featured nut:" + m1
   document.f1.messageHere.value=m1 + ", " + m2
<b onmouseover="goNuts('walnuts', 'get some today')" onmouseout="clrMessage()">big</b>
<b onmouseover="goNuts('cashews', 'the nut of kings')" onmouseout="clrMessage()">medium</b>

variables/string-int conversion

Javascript uses double-quotes for strings and assumes anything not in quotes is a variable. Unlike bash, when a variable is created javascript secretely remembers whether it is a number or a string (or something else.) For examples (click these):
<tt onclick="a=5; alert(a+7)"></tt>, <tt onclick="a='5'; alert(a+7)"></tt> In each case, javascript used number plus or string plus based on how you first made a.

Anything you read from a textbox counts as a string. If you want to treat it as a number, you need to use x=parseInt(location.value, 10). The 10 is the base in which the number is written. A simple example of parseInt: <tt onclick="x=parseInt('45',10)+5;alert(x)"></tt> and one using the base: <tt onclick="x=parseInt('100',3);alert(x)"></tt>

Contrary-wise, anything you put into a textbox should be a string. In fact, javascript will turn things into string if it is obvious (which is why a="5";alert(a+7) works -- it assumes you meant "7".) You may explicitly turn numbers into strings with x.toString(10) (once again, the 10 is the base in which you want the string written.) For example: <tt onclick="a=12;alert(a.toString(10)+5)"></tt> or using a different base: <tt onclick="a=12;alert(a.toString(3))"></tt>

On input like "abc" parseInt will give the answer "NaN" (not a number.) A function to check for this is isNaN, as in val1=parseInt(forms[0].dog.value); if(isNaN(val1)) val1=0;

For technical reasons, the first time you use a new variable inside a function, var should come in front of it (an example below, in "loops") [var makes it a local variable.]


An if in javascript is written if(test) { lines }. As in bash, there is the same optional else: if(test) { lines } else {falseLines}. Curly braces are used instead of then/fi. The test uses <, >, <=, >=, != (not equals) and == (equals compare.) Ifs may be used inside of other ifs (as in Excel/bash.) AND and OR are written as && and ||, respectively. Sample ifs:

if(a<=10) { a=10 }

if(b=="big" && c=="cheese")
 { b="big cheese"; c=""; }

if(n<1 || n>10) { alert("Number must be 1 to 10") }
else if(n>1000)    { alert("Number must be less than 1000") }
else                  { alert("Thanks, dude") }

Note that the rules say the else should have had a {} after it (like a bash then-fi.) Javascript lets you skip this if there is an if just after.


javascript does not have bash's "magic" for a in... loop, but there isn't as much need for it. It does have the while loop, which looks like: while(test) {lines}. The do/done are replaced by curly braces. The test is the same as for a javascript if.

Sample code

var n=parseInt(document.forms[0].elements[0].value,10); // get the number
var i=1;
 { i=i*2; }
// Ex: if the input was 13, i is 16
document.forms[0].elements[1].value="Next power of 2 is "+i;


A javascript comment starts with // and goes to the end of the line (like # in bash.) It does not need to be the first thing on the line (while example, above.)