Javascript

why Javascript?

Most beginning web developers would rather avoid Javascript altogether, given the choice. Javascript can be a tricky, tempermental language to work with. It looks stranger than HTML or CSS, and it is not nearly so easy to divine what a line a Javascript is doing.

So why would we use such a thing? Unfortunately, Javascript is the only way to accomplish certain tasks. In general, Javascript is used whenever we need to process logic on the client side. In other words, if we are to do any true programming which will run on the user's browser, Javascript is our only option.

Remember that client side processing is a lot different than server side processing. The majority of your tasks may well be better suited for the webserver. But features relating specifically to the user interface live in Javascript's domain.

cross-browser testing

No language requires more corss-browser testing than Javascript. Sadly, browser makers have been unable to agree on an exact implementation. Javascript that works famously in one browser fails miserably in another. Most of the time there are workarounds, sometimes there are not. If you have no control over the browser your audience is using, make sure to test thoroughly in two or three of the most popular browsers to make sure you have working code. Attention to "details" like this will separate you from all the mere aspiring webslaves out there. Bondage to testing is what makes a webslave great.

I would love to provide all the solutions to your Javascript problems in this text, neatly numbered and identified to help you avoid the pain your forebears have gone through. This is not possible however, as there are too many variations in browser interpretation of Javascript. Many are documented on the web, but nothing substitutes testing when it comes to honing your website.

Javascript in the HTML header

Place Javascript functions (more on these below) in the HTML header of your document. Tell the browser it's Javascript with the <script> tag. It is also considered best practice to enclose the script itself as an HTML comment, as some less intelligent browsers apparently print the script onscreen (duh).

<head>
<script language="Javascript">
<!--
[Javascript code here]
//-->
</script>
</head>

Your Javascript code may be written to execute upon page load or upon any particular action on the part of the user. Placing this code in the header is one method of loading Javascript with your page.

loading an external Javascript file

The other way to load in Javascript with a webpage is by creating an external file. Just as with CSS files, Javascript files (with the extension .js) can be handy to use for the purpose of loading them to multiple webpages. No need to repeat all that code in each page's HTML header.

With Javascript, simply give the "src" attribute a value in the script element. It is reminiscint of how we load images:

<head>
<script language="Javascript" src="factory.js">
</script>
</head>

basic function syntax

Functions are units of work that we give names to. Giving names to them allows us to call them by name when we need them. When our webpage loads, most or all of our functions are loaded into memory, but they are not immediately executed. They are lying in wait for the user to take some action that we have set to trigger the function.

the function keyword

Name a function by using the "function" keyword and following it up with your creative name and a set of parentheses:

function openWin() {
     myWin= open("day.html", "popup", "width=520,height=370,scrollbars=yes,status=yes,toolbar=no,menu=no");
}

The name of our function is openWin.

parentheses

The parentheses immediately following openWin are in place to receive variables if necessary. In some cases you will define which variable values the function will require to... well, function. We won't cover how to pass variables to functions in this text, but if your project requires advanced Javascript programming, there are many resources available to you. For now, just put in the parentheses and congratulate yourself on knowing they pertain to passing variables to the function.

The parentheses following the "open" method in the example above are also passing variables. In this case they are passing them into "open" to define the window that is to be drawn.

brackets

The brackets {} following the function name exist to define the actions of the function. The code you write after the opening bracket { will execute line-by-line until the closing bracket } is encountered.

semicolons

A semicolon defines a statement in Javascript. There is only one statement in the openWin function. If there had been more, each would have executed to completion before the next would begin. This means that Javascript, unlike HTML or CSS, is a procedural language. That's a fancy way of saying you can write logic in a step-by-step manner to accomplish more complex tasks.

<script language="Javascript">
<!--
function myFunction() {
     [statement 1];
     [statement 2];
     [statement 3];
     [statement 4];
}
//-->
</script>

calling functions

Assuming you have a groovy function you'd like to execute, let's review our options for calling the function. Exactly when you call a function can be as important as what the function itself does.

<body> onLoad

Sometimes you want a function to execute immediately after your webpage loads. Perhaps we want our popup window function openWin to run right away. We can call the function immediately using the onLoad keyword in our opening <body> tag:

<body onLoad="openWin()">

The function will run upon page load.

onClick

Perhaps the most common way to execute a function is on a click action. The onClick keyword modifies the <a> tag to call the function:

<a href="anotherpage.html" onClick="openWin()">click here</a>

This will not only load anotherpage.html, but it will run the openWin function, loading day.html into a new window.

onMouseover

Triggering Javascript functions whenever a user mouses over a link can get chaotic, but it can be useful for some things. The most familiar is the rollover button. For any usage, when a user mouses over the linked area, the onMouseover action is invoked. The onMouseover link also goes in the <a> tag:

<a href="anotherpage.html" onMouseover="someFunction()"><img src="click_here.gif"></a>

In this case we are linking an image to the onMouseover event.

onMouseout

When the cursor moves out of the linked area, we say that a mouseout event has occurred. The onMouseout keyword is most commonly used for rollover buttons and dynamic menus. Use it in the <a> tag:

<a href="anotherpage.html" onMouseout="someFunction()">click here</a>

onSubmit

onSubmit is an action keyword used in the <form> tag, since the only things we submit within HTML are forms. Often this is used to run form validation functions, to check that the data the user has entered in the form is of proper character:

<form action="../cgi-bin/register.cgi" method="post" onSubmit="checkForm()">
[input fields]
</form>

Depending on how the checkForm() function is written, the form submission may be halted in order for the user to correct some of the data in the form.

Steal This Code

the etiquette of stealing

It will take you a lot of practice to master Javascript. Above we have outlined only some of the basic concepts of the language, and omitted many. This book contends that Javascript need not be mastered by the wholistic web developer. Tough problems may require compromise or outside help, but in general you don't need to be a total Javascript master in order to be a worthy webslave. One of the reasons for this is that a basic understanding of Javascript will be sufficient to adapt existing code.

Existing code? That's right. There are millions of lines of Javascript on the internet just waiting for you to adapt them to your own needs, just like HTML. Simply "view source" on any scripted webpage and grab what you want to play with. You can change portions of the code to satisfy your own goals in design, on your pages. Is this legal, to "steal" code and adapt it? Absolutely. What is not legal is to lift the content of other websites and place it on your own without obtaining permission to do so.

The rest of this section is devoted to code you can steal right now.

submitting forms with links

Indeed the path of the web designer soon turns down the road of development; you are no longer content to let the robots write your code. The truth is that many attractive and functional elements of website design are somewhat tricky to implement, and require your full attention to customize at the code level.

In computing, everything has a name. Therefore if you want to gain control over it, you need it to provide it a name and call it by that name. Assign a value to the name attribute in your targeted form:

<form name="form1" method="post" action="../cgi-bin/mailinglist.cgi">
[input fields]
</form>

In addition to, or in place of, a submit button, we can trigger our form to submit by placing some Javascript in the href value of an old <a> tag:

<a href="javascript:document.forms['form1'].submit();">[text or an image]</a>

This <a> tag will link the submit action to whatever text or images you wrap in it.

The Javascript will look a little foreign to you at first (and probably for a long while!) but it really makes a lot of sense sometimes. Javascript is an object-oriented language, and the above code is a straightforward example of specifying a method (the action) and the exact object it should act upon. The method is submit(), and it is to act upon the form "form1" which is a child object of the document object (which represents your .html page as a whole).

That's a bit of an unpleasant mouthful, but that's OO (object oriented programming). Fortunately, if your goal is to become a wholistic web developer, you may not need to become all that intimate with this programming concept. But you will need to have a little Javascript understanding in your back pocket before ascending to true webslavery, which is why we've devoted a section to it in this book.



last modified

Sometimes Javascript can be inserted directly into the body of your HTML, surrounded by <script> tags of course. Setting a "last modified" trigger is an example of doing this. The below code will actually "ask" the file when it was last changed and write the result to the screen:

<script language="Javascript">
var modifieddate=document.lastModified
document.write(modifieddate)
</script>

The format of the timestamp result depends on the browser. Internet Explorer 6 gives us this:

12/01/2003 20:50:32

Netscape 7 gives me this:

Tue, 02 Dec 2003 01:50:32 GMT

These results were for the same document... obviously a different format, but worse: based on different time zones! Let's check the UNIX timestamp on the file:

-rw-r--r-- 1 mindmine mindmine 6576 Dec 1 19:50 index.html

Netscape gives us the file's timestamp in Greenwich Mean Time (GMT) while Internet Explorer took the file's timestamp on my webserver (which is an hour behind me in the Midwest) and translated it to my time zone, an hour later. The onscreen result in both cases was different than the actual timestamp, but both deadly accurate in their own way.

alert

As we've discussed, Javascript gives us access to some advanced user interface features available to the browser. One such feature is the Javascript alert box. The alert is a standard pop-up dialogue box that requires the user to click "OK" before proceeding. Click this link for an example if you are reading this online (it will look a bit different in each browser).

The alert is constructed as a function up in the HTML header, and waits for an event to trigger it:

<script language="Javascript">
<!--
function myAlert () {
    alert("Please read the agreement.");
}
//-->
</script>

Let's suppose we'd like to execute the function myAlert when a certain radio button is selected. Using the onClick keyword, this is cake:

Did you read the licensing agreement?<br><input type="radio" name="agreement" value="yes">yes
<input type="radio" name="agreement" value="no" onClick="myAlert()">no

Notice the onClick event is only set when the user clicks "no". Depending on the browser, the alert may also be accompanied by a sound as the default behavior of the alert. The result:

Did you read the licensing agreement?
yes no

You can also set the alert to execute upon load of the page, or upon form submission (onSubmit). Try calling the myAlert function (which you can give your own name to if you wish) with these other events for practice.

cofirm

Close cousin to the alert dialogue is the Javascript confirm. Dialogue is a more fitting term when talking about "confirm", as confirm gives the user an opportunity to cancel before proceeding, as opposed to alert's decisive "OK".

Write a confirm function to capture the result of the user's choice. The way to capture a result is to assign a variable to it. We'll call our variable "result". We'll call our function "confirmBox". Depending on the value of "result" (confirm returns "true" for "OK" and "false" for "Cancel") we'll return the appropriate value to the method that called us, probably onSubmit, using an if-else statement.

<script language="Javascript">
<!--
function comfirmBox() {
     var result = confirm("Proceed?");
     if (result == true) {
        return true;
     }
     else {
        return false;
     }
}
//-->
</script>

The above code handles the creation of the confirm dialogue and the handling of the user's selection. If you have called this function with onSubmit, a return of "true" (user clicks "OK") would then submit the form. Here is an example of a form which calls the confirmBox function (we'll leave the action blank for now... a form submission will just take us to the top of the page):

<form method="post" action="" onSubmit="return confirmBox()">
<input type="submit" value="Go">
</form>

The keyword "return" expects output from the function, which responds with "return true" or "return false".

Confirm can be handy to force at least a brief reconsideration before form submission.

field focus

Focus is a term for where the browser's attention is at a given moment. This is most often applied to input fields, since we often wish to prompt a user proactively with a blinking cursor in the field we want noticed. Javascript offers the focus() method for this purpose.

Let's first create a form with various fields in which we might want to establish focus. We'll be sure to name the form, and the fields to of course, as we will be calling them by name in Javascript.

<form name="myCoolForm" method="post" action="">
first name: <input type="text" name="first_name"><br>
last name: <input type="text" name="last_name"><br>
occupation: <input type="text" name="occupation"><br>
age: <input type="text" name="age">
</form>

Here is our crude form:
first name:
last name:
occupation:
age:
Reference myCoolForm in a Javascript function, followed by the name of your important field, and apply focus:

<script language="Javascript">
function putFocus() {
     myCoolForm.first_name.focus();
}
</script>

We can then trigger our function with one of our event handlers like onClick. For instance, click here to apply the field focus to myCoolForm.

Here is the code for that link:

<a href="#" onClick="putFocus()">click here</a>

More often, we may want to apply the focus upon page load:

<body onLoad="putFocus()">

Focus can also be very effective when used along with alert. Alert the user as to the error, and focus on the field that needs correcting.

writing to the status bar

The status bar is found at the bottom left of most browsers. It shows by default but keep in mind: it can be turned off by the user in most cases. However, the majority of people don't do this, so writing to the status bar is plenty worth it.

This very webpage has status bar text ("The Webslave's Handbook"); this is how it was done. Just a bit of Javascript in the header, invoking the onload event through the window object. This really isn't any different than using <body> onLoad.

<script language="Javascript">
window.onload=new Function('window.status="The Webslave\'s Handbook"')
</script>

Cut and paste this code, modifying the important text, and you're done. Note the \ in Webslave\'s. We need to "escape" the single quote so the browser's Javascript parser doesn't think it signifies the end of the text.

dropdown menus for navigation

Dropdown menus are sometimes useful to present a choice of links to other pages. For this, prepare a function as below, naming the elements you'll need to control.

<script language="Javascript">
function goTo() {
onClick =
window.location =
document.linkForm.linker.options[document.linkForm.linker.selectedIndex].value
}
</script>

The companion HTML will look something like this:

<form name="linkForm">
<select class="type1" name="linker" onChange="goTo()">
<option SELECTED>jump to...
<option value="html.html">HTML section
<option value="css.html">CSS section
<option value="perl.html">Perl section
</select>

The names that need to match between the form and the function are color coded. The name of the form I chose in this case is linkForm. The name of the <select> menu itself is linker. The function that will execute the link is called goTo. We are using a new event handler now in the <select> tag, onChange. When the selection is changed by the user, the goTo function is called, and the browser window loads a new page.

playing sounds

Sound event handling has three components. First and foremost you need to "embed" the audio in the page, so it is loaded with everything else up front. The <embed> tag has a couple of notable options, including the ability to autostart the sound on page load. If you want the sound to play immediately, you need nothing else than the below code somewhere in the body of the HTML:

<embed src="sounds/cheer.wav" autostart=true hidden=true name="cheer">

The "hidden" option allows you to hide the "player" which, if hidden is set to false, may be rendered at various sizes on the screen depending on the audio plug-in your are using. Try setting hidden to false and viewing the page in a few different browsers. You may want to use this feature, you may not, but poor cross-compatability if you experience it would be a vote against.

If you want the play the sound only when triggered by a specific event, set autostart=false and include the following function in the <head> of your document:

<script language="Javascript">
function playSound(soundobj) {
var thissound= eval("document."+soundobj);
thissound.Play();
</script>

Then, you can call the playSound function, feeding it the name of the embedded sound which it accepts between the parens ().

<a href="#" onClick="playSound('cheer')">click</a>

Remember that "cheer" refers to the value of the name attribute in our <embed> tag, above. Here is the link we've made:

click

We could also call the function on another event. How about mouse over?

<a href="#" onMouseover="playSound('cheer')">mouse over here</a>

mouse over here

If needed, we could embed twenty sound files, being sure to give them unique name values, and call them by them on various events using the same playSound function. Be careful not to create a painfully long page load, however, if the weight of your sound files all together is too large. This would only be apprpriate for relatively short sound clips.

***

On to The Back End

Back to index