Week 13

* Assignment *

Questions from last time?


Chapter 19: Introducing JavaScript

You can add interactivity to your Web pages using small programs, called scripts, that are executed by the Web browser. The most popular scripting language for the Web is JavaScript (which is not related at all to the full-blown programming language named Java, by the way). Although a scripting language like JavaScript is a programming language, it is designed to be simpler to read and implement than a full programming language such as C++ or Java.

JavaScripts can be embedded right in the HTML code of your Web page (in either the head or the body of the page), or the scripts can be stored in external files separate from the Web page.

Scripts can do many things, such as changing the content of a page (to display the time or refer to a user by a previously entered name, for example), or react to events (such as the user hovering over or clicking on certain page elements—which can be used to make images change or make parts of the page appear/disappear), or move elements of the page around (by changing the position attributes of the element), or open new windows, or identify what browser the user is using (to redirect them to special pages for that browser), or to store and retrieve information in 'cookies' (which are bits of data stored on the user's machine). Scripts (along with HTML and CSS) are the basis for what is called Dynamic HTML (DHTML), which allows for Web pages that are more interactive or animated -- but the term DHTML has fallen out of favor because people associate it with older dynamic Web page practices that are out of style.

We have a whole 3-credit course at UNM-LA (IT 148) about JavaScript and DHTML, so what we are going to cover today is just a sampling, and you are certainly not expected to understand JavaScript after one lesson. You can, however, use scripts in your Web pages even without fully understanding how to write scripts. There are many resources on the Web that demonstrate how to achieve certain effects with JavaScript, and you can often copy these techniques for use in your own pages.


Scripts in the Body

You can put scripts in several places. One option is to place the script within the HTML of the body of your Web page. As the page is loaded and rendered by the browser, the script will be executed. You just place the JavaScript commands within <script>...</script> tags within the HTML code of the body, like this:

<script type="text/javascript">
JavaScript code goes here

There is also a language="javascript" attribute for the <script> tag, but it is only needed by old browsers, so I recommend not using it. The chances of anyone still using a browser old enough to require it are small.

Note that embedding JavaScripts right in the HTML code is not the preferred method, for the same reasons that inline CSS styles are generally avoided (to keep your HTML, JavaScript, and CSS as separated as possible). We will see later how to put your JavaScript in an external file...but for these first simple examples, we will just put the JavaScript right into the body of the HTML.

The example01.html page is a very simple example of a script in the body that is automatically executed as the page is rendered. All it does is write the words "Hello World!" into the body of the page at the location of the script (which is located within a paragraph). View the source code of that page (the HTML of the body is shown below). This is not a very useful example of JavaScript, since we could have simple put the text 'Hello World!' into the HTML directly, of course, but bear with me and we will get to more complex examples.

     <h1>JavaScript Example 01</h1>
     <p>The script in the body of the document.</p>
     <script type="text/javascript">
     document.write('Hello World!');

Notice that within the JavaScript code itself I have used single quotes around 'Hello World!'. HTML and JavaScript allow you to use either single or double quotes in most places, but it will matter when we embed JavaScript commands within a line of HTML code (you don't want a double quote within the JavaScript prematurely ending an HTML attribute that is surrounded by double quotes), so I recommend always using double quotes in HTML and single quotes in JavaScript.

For a more useful example, example02.html shows how a JavaScript can insert something besides simple text. In this case it uses the JavaScript Date() constructor to put the current date+time into a variable named d, and then writes the value of d into the document at the location of the script. Look at the script itself:

<script type="text/javascript">
     var d=new Date();

The first of the two lines within the script says we are declaring a variable named d and also defining it to have the current date/time value in it. (Note that I could have been less formal and left out the "var" and it would work just fine.) The next line uses what is called the "write method" of the "document object" to write the value of the variable d into the document.

The semicolon at the end of each line of JavaScript code is optional, but if you want to put two JavaScripts commands on one line, you must use the semicolon between them.


External Scripts

You can also store the JavaScript code in an external file and reference it from within the HTML code. This allows the same code to be used by several different Web pages on your site. It also hides the script from ancient Web browsers that don't understand it. More importantly nowadays, putting your JavaScript code in external file gets it out of the HTML so that it won't be flagged as an error by the HTML validators (scripts that contain < or / symbols, for example, can cause the validator to complain since it will try to interpret these symbols as parts of opening and closing tags).

For example, example03.html is the same as the previous example, but with the JavaScript command stored in the external text file time.js

Note that the time.js file is a plain text file, and it contains only the two JavaScript lines:

var d=new Date();

...and it does NOT contain the <script>...</script> tags! In the body of the document we now just have:

<script type="text/javascript" src="time.js">

...within the paragraph that displays the date/time. Note the src attribute that specifies the location of the script file. Script files are plain text files, and people usually use the file extension .js to indicate that they contain JavaScript. There is a charset="encoding" attribute that can also be used in the <script> tag here if your text file uses some unusual encoding (because it includes foreign characters, perhaps), but you shouldn't normally need to worry about this (I usually just save my text files with the same utf-8 encoding is use for my HTML files, but you shouldn't have any problems if your text editor stores your text file in the windows-1252 or x-mac-roman encodings used by default on PCs and Macs.


Scripts in the Head. Functions.

Scripts can also be stored in the head of the document. Such scripts would be executed when the page loads (and this is sometimes done to set up variables and initial values), but normally the scripts that are placed in the head of the document contain functions. Functions are blocks of JavaScript code that do not execute until they are called by other JavaScript commands. You can also have <script>...</script> tags in the head of the document that link to an external JavaScript file (the same way as it's done in the body).

The file example04.html has a function in the head of the document. This function is called by a script that is in the body of the document.

Note that the script in the body has to come AFTER the empty paragraph that has id="placeholder" because that paragraph must already be in place so that the JavaScript can target it (pages are rendered from top to bottom by Web browsers).

Here is the body of the example04.html Web page:

     <meta charset="UTF-8" />
     <title>JavaScript Example 04</title>

     <script type="text/javascript">
          function putInTheText()
          var d=new Date();

     <h1>JavaScript Example 04</h1>
     <p>This page has a function stored in the head that is called by
      a script in the body.</p>

     <p id="placeholder"></p>

     <script type="text/javascript">

Note the format of the function that is in the head of example04.html (shown in red above). The word "function" indicates that this code is a function, and the function has the name putInTheText(). JavaScript authors often make names from words run together with capital letters emphasizing the start of subsequent words as shown.

The parentheses are part of the function name. The code that calls the function can "pass" values to the function by putting the values inside the parentheses (in such cases, the function would have a variable name in the parentheses for each passed value). Functions can also return values to the calling code. But neither of these things is done in this example here.

The curly braces enclose the code of the function (just two lines in this simple case). The first line of this function's code declares the variable d and puts the current date/time into it using the Date() constructor. The second line locates the element of the document that has id="placeholder" (the empty paragraph in the body with this id, shown in orange), and uses the innerHTML method of that element to change its text content to be the date/time contained in variable d.


Avoiding Scripts in the Head?

Note that the textbook author specifically warns against putting scripts in the <head> of the document if it can be avoided. This is because when the Web page is being loaded, whenever the browser runs up to a script, it it stop and load that script and interpret it... and it will not continue downloading and rendering the rest of the page elements until it has done so. This can cause a delay if the script is long and complicated.

So, the author recommends putting scripts at the END of the body, just before the </body> tag, so that they do not cause delay in loading and rendering the rest of the Web page. HOWEVER, this does not work for all scripts (depending on what the script needs to do, and when it needs to be called). In example04.html, for example, the script must appear before the line that calls it in the body, so it would not work to put this script at the end of the body.

In example06.html (see later), I put the function script at the end of the body (and it works fine in that case because that script is not called until a button is pressed).

If a script MUST be in the head of the documant, it should be placed at the end of the head so that it does not delay the loading of any external style sheets.

This all applies even if the JavaScript is kept externally. When the Web browser runs up against the link to the external file, it stops all other rendering and downloading until it has loaded and parsed that script. So, links to external scripts should also go at the end of the body if possible (as I did in example09.html later).


Triggering Scripts

In many cases, you don't want a script to execute until the user does something specific, such as clicks on a link or points at an element on the page. These specific actions are called intrinsic events (or just events for short). Events also occur when the Web page loads, or when the user leaves the page, or when the user interacts with form elements. The browser is constantly watching for events to occur, and you can set your JavaScript routines to be triggered by various events.

Different events apply to some Web page elements and not others. Page 418 of the textbook lists which events apply to which elements. In old Web browsers, the <a> tag could respond to the greatest variety of events, so you will often see links used as the tag used to trigger a JavaScript routine.

In example05.html there is a link on the word "time" that is used to trigger the appearance of an alert box. Note that because I didn't want the link to actually go anywhere when click upon, I made it a null link by using the href="javascript:;" (remember to include both the colon and the semicolon). This null link says it's going to run a JavaScript command...but then no JavaScript command is given (there is nothing between the colon and semicolon), so the link does nothing.

BUT, clicking on the link DOES cause an onclick event, and the script in the onclick attribute of the link is then triggered. The HTML of the link looks like this:

<a href="javascript:;" onclick="alert('It is now '+Date())">time</a>

The script will open an alert dialog box which will contain the text "It is now " followed by the current date/time. Notice how it was necessary to use single-quotes in the script because the script is surrounded by double-quotes.

If you need to use a single quote inside a JavaScript line that is enclosed within single-quotes, you can precede it with a backslash escape character, like this:

onclick="alert('It\'s now '+Date())

Note that clicking on the image of Totoro at the bottom of the example05 page will also trigger an alert box


A List of Intrinsic Events

Below is a list of some intrinsic events that can be used to trigger a JavaScript routine.

onload occurs when a page loads, and it applies to the <body> tag. (It also can be used with framesets, but we aren't covering those in this course.)

onunload occurs when the page is unloaded, and it applies to the <body> tag. A page unloads whenever a user close the page, or when the user clicks on a link that leads to another page that opens in the same browser window.

onclick occurs when the user clicks on an element. This event (and the other 'mouse' events below) applies to most elements.

ondblclick occurs when the user clicks on an element.

onmousedown occurs when the user presses the mouse button down on an element (it does not wait for the mouse button to be released).

onmouseup occurs when the user releases the mouse button over an element.

onmouseover occurs when the user moves the mouse cursor so that it enters the boundary of an element.

onmouseout occurs when the user moves the mouse cursor so that it passes out from within the boundary of an element.

onmousemove occurs when the user moves the mouse cursor around within the boundary of an element.

onfocus occurs when the user selects a element either with the mouse of by tabbing to it. The element (such as a link or element in a form) is then said to "have focus."

onblur occurs when an element that 'had focus' loses focus (because some other element was given focus).

onkeypress occurs when the user types a character in a form element.

onkeydown occurs when the user types a character in a form element (this occurs when the key is pressed, and does not wait for the key to be released).

onkeyup occurs when the user releases the key upon typing a character in a form element.

onselect occurs when the user selects text within a form element such as a text field or textarea.

onchange occurs when the user has changed the value of a form element.

onsubmit occurs when the user presses a submit button in a form. This event applies to the <form> tag, and NOT to the submit button itself.

onreset occurs when the user presses a reset button in a form. This event applies to the <form> tag, and NOT to the reset button itself.


Setting the Default Scripting Language

With internal or external scripts enclosed in or referenced by a <script> tag, you can specify the scripting language used (which might be something other than JavaScript) by using the type attribute. But for the scripts embedded in the handlers of triggers (such as onclick), there is no way to specify the language except by using a <meta> in the head of the document. For JavaScript, you would use:

<meta http-equiv="Content-Script-Type" content="text/javascript" />

BUT, while HTML documents supposedly require such a line in order to be valid (if they contain embedded scripts), I have never seen a validator complain if the line is not included, so I leave this out.


Using Buttons to Execute Scripts

Remember the <button>...</button> tags that we used as an alternate method for creating Submit and Reset buttons (which could include text and/or images, and be formatted with CSS)? You can use that tag to make buttons that trigger JavaScript routines.

See example06.html for examples of this. The first button is unformatted by CSS and brings up a alert box when you click on it (it has the Javascript in its onclick handler). The second button is the same, but has CSS applied to change its look. The third button calls a JavaScript function (which I located at the end of the body) and replaces some text in the paragraph below the button with the current date/time. Here is the head and body from example06.html:

<meta charset="UTF-8" />
<title>JavaScript Example 06</title>

<style type="text/css">
     .timebutton {
     background-color: orange;
     color: red;
     font: bold 20px Arial;
     border: 5px outset orange;

<h1>JavaScript Example 06</h1>
<p>Using buttons to trigger JavaScript routines:</p>
<button type="button" name="datetime"
onclick="alert('It is now '+Date())"
>Click me for the time!</button>
<p>The button above is unformatted, but the one below uses style <strong>.timebutton</strong> to
make it more interesting:</p>
<button type="button" name="datetime2" class="timebutton" onclick="alert('It is now '+Date())">Click me for the time!</button>
<p>Clicking on the button below calls a function in the
head of the document that replaces text that is in a &lt;span&gt;...&lt;/span&gt; in the
paragraph below it:</p>

<button type="button" name="datetime3" class="timebutton" onclick="putInTheText()">Click
to see the time below</button>

<p>The current time is <span id="placeholder">(the time will appear here)</span></p>

<script type="text/javascript">
     function putInTheText()
     var d=new Date();



Displaying Messages to Users Without JavaScript

If your Web page uses JavaScript to trigger changes or display some information, users who don't have JavaScript running will miss this. Some people, for example, have JavaScript turned off in their browsers to avoid seeing any pop-up ads that use JavaScript to work.

You can display messages to these users with the <noscript>...</noscript> tags. This is a block element, so don't try to put it inside paragraphs—use it as a separate block, and be sure to enclose any text or images it contains inside paragraphs or divs to avoid validation errors. Example:

    <p>Sorry, but the pop-up information on the map below will not
    work if you have JavaScript disabled in your browser settings.</p>


Comments in JavaScript

You can insert comments in JavaScript code in two ways. You can insert single-line comments by using // (two slashes) at the start of the comment. This can be on its own line, or it can appear after some Javascript on a line. You can insert multi-line comments by beginning them with /* (slash, asterisk) and ending them with */ (asterisk, slash). Example:

<script type="text/javascript">
/* The code below is for making the
     paragraphs at the start of the page.
     Change by T. Beach on May 1, 2010  */

// Write a heading first.
document.write("<h1>This is a heading</h1>");
document.write("<p>This is a paragraph.</p>");             // This is para 1
document.write("<p>This is another paragraph.</p>");    //This is para 2



Examples of JavaScript

Above we discussed scripts in general (where they are stored, how they are triggered, etc.). Now I'll give you a taste of JavaScript by showing a few examples.


Inserting Dates and Times

JavaScript has "date objects" that can contain dates and times (the variable d that was used in some earlier examples was a date object). See example07.html to see simple scripts that insert the date and time into a Web page when it is loaded.

The first script on the page inserts the contents of the date object d in its default format using:

var d = new Date();

...where the Date() constructor is used to make a new date object (the variable d), and insert the current date+time into d. Then the write method of the document object is used to write the value of d into the Web page at that point, in the default format that looks like: Sat May 01 2010 21:53:29 GMT-0600 (MST) .

But there are many "methods" that are defined for date objects that can manipulate the content of a date object. In the second script on the example07 page, the "toDateString()" method is used to pull out just the date part of the date object d so that it can be written with this line:


The date format this produced (at least in the browser/OS combination I was using when I created this page) looks like: Sat May 01 2010 .

The next script on that page uses the "toLocaleDateString()" method to pull out just the date part of the date object d and format it using locale conventions. This results in a date format (which you might like better) that looks like: 05/01/2010 (but, again, it way look different depending on your machine).

The last script on the example07 page uses the "toLocaleTimeString()" method of the date object to pull out just the time part and format it by locale conventions so it can be written into the document, and that format that I got looks like: 21:53:29.

As you can see, the time format I got was in a 24-hour format (although this will vary depending on your computer). In order to get a consistent display the time in 12-hour format with am/pm, I had to use some more date object methods and JavaScript programming. All of the date object methods can be found on the W3schools Web site. In fact, a whole tutorial on learning JavaScript can be found on that site.

The example08.html file shows the result. Because the JavaScript code for this routine contains < symbols, an HTML validator might complain (it thinks the < symbols are the start of an HTML tag), so I stored the JavaScript in an external file (named time2.js). The routine is shown below with comments:

var d=new Date();           // puts the date+time in date object variable d
ap="am";                        // sets the value of the variable ap to "am"
h=d.getHours();              // pulls the hours number (0-23) out of d
m=d.getMinutes();          // pulls the minutes number (0-59) out of d
s=d.getSeconds();           // pulls the seconds number (0-59) out of d
if (h>11) { ap = "pm"; }       // if the hour if greater than 11, set ap to "pm"
if (h>12) { h = h-12; }           // if the hour if greater than 12, subtract 12 from it
if (h==0) { h = 12; }              // if the hour is 0 (midnight), set it to 12 for 12 am
if (m<10) { m = "0" + m; }  // if minutes is less than 10, add on the leading zero
if (s<10) { s = "0" + s; }       // if seconds is less than 10, add on the leading zero
document.write(h + ":" + m + ":" + s + " " + ap);
/* the last line above writes the values of the hours, minutes, and seconds into the document, separated by colons, and adds on a space and the the value of ap (which is either am or pm) */

The if statements in the routine above are examples of conditional statements, which programming languages use to decide whether or not to perform certain steps.

If you want to leave off the seconds from the time display, you can just remove those parts of the code. Similar methods allow you to pull out the different parts of the date and format them as desired.

The time is inserted into the example08.html page by this HTML that calls the external JavaScript routine:

<p>It is now
<script type="text/javascript" src="time2.js">


The last thing I did with the date object was to take the routine for formatting the time and combine it with the JavaScript setTimeout() method. This method allows you to set up the triggering of scripts to execute after a time delay. I used this to trigger the time conversion and display routine ever half second to make a continuously running clock display. The result can be seen in the example09.html file.

If you look at the HTML of example09, you will see that the JavaScript routine's <script> tag is ilocated at the end of the body of the document. The script itself in the external file (named clock.js) is now a function (because I added the first line function mytime() and surrounded the routine in curly braces) named mytime(). The function is triggered for the first time when the page is done loading because of the event handler in the body tag:

<body onload="mytime()">

...and then the new last line in the mytime() function:


...sets a timeout event that will execute the mytime() function again ever half second. This way, the time display is continuously re-triggered every half second.


Opening New Windows

Another thing JavaScript can do is open a new window without using the target attribute of a link, and we can also control how large the window is and where it is located on the screen.

The example10.html page has several examples. Let's go see!

You can open a page in a new window using the following JavaScript in a link:

<a href="javascript:;" onclick="myWindow=window.open('page.html',
name', 'height=h,width=w,top=t,left=l,scrollbars=yes,
); myWindow.focus()">
link text</a>

...where page.html is the URL of the page you want to appear in the window, and name is the name used to identify the window if you want to target future links to it (you can leave the 'name' part out to target a new _blank window). The items in orange are also optional, either individually or as a whole. If you leave them out, the new window will get a default size and position. The h, w, t, and l above are numbers (in pixels) specifying the length and width, and the distance from the top and left side of the screen for the new window. The "browser chrome" items listed actually have default values of yes, so unless you want to specifically set them to no, you can leave them out (some browsers may not let scripts turn off certain chrome items). IMPORTANT: There should be no spaces within the orange items.

The myWindow.focus() command (after the semicolon) ensures that your new window will get focus and come to the front when it's opened (or when it's called upon again, if the same link is clicked again or another page is targeted tot he same window). Otherwise, the page may load into the window, but the window won't come to the front where the user can see it.

So here is the less cluttered version that will open the page (with URL of page.html) in a new windows of default size and position:

<a href="javascript:;" onclick="myWindow=window.open('page.html'); myWindow.focus()">link text</a>

...where page.html is the URL of the page you want to appear in the new window.


Rollover Image Change

A rollover image change is a dynamic effect where an image on the page changes to a different image when the user points at the image. When we learned how to do rollover effects with CSS, we mentioned that in the old days this had to be done using JavaScript. Well, using JavaScript to do rollovers still works, of course.


The rollover above can also be found on the example11.html page. That page also shows that the rollover change of the image can also be triggered by rolling over a different element. The code for making the above rollover is shown below:

<img src="totoro.jpg" id="totoropic"
alt="Totoro" width="96" height="123" />

Note that is is always the element that has id="totoropic" that is being changed. Changing the src of the image does not change the fact that it is still located in the same place in the HTML and still has the same id.


Click Image Change

What we were NOT able to do with CSS was make an image change when we clicked on something, and have the image stay changed. But we can achieve this dynamic effect with JavaScript.

The imageChange.html page shows that it's easy to use two links to change the image back and forth between two images. Here is the code for the two links and the image:

<p><a href="javascript:;"
<p><a href="javascript:;"
<p><img id="totoro" src="totoro.jpg" alt="totoro pic" width="96"
      height="123" /></p>

Did you notice that the two images are referenced differently in the links ('totoro.jpg' vs. chim.src)? That's because the chimp.jpg image was preloaded by a script at the end of the body:

<script type="text/javascript">
     chim = new Image(96,123)
     chim.src = 'chimp.jpg'

This loads up the chimp.jpg image into the browser's cache so it's ready to pop into place instantly after the click (and there is no delay waiting for the image to download). The script ends up defining the global variable chim.src that can be used in other scripts on the Web page to reference the image. Actually, I think that once it has been loaded and the image is in the cache, it would be equally fast to just use 'chimp.jpg' instead of chim.src in the link above.


As long as I was at it, I made imageChange2.html, which demonstrates that a click on one link can trigger a change in multiple images. It just requires additional JavaScript commands (separated by semicolons!) in the onclick handler scripts.


Do you remember the dynamic CSS example where pointing at one of several little thumbnail images would make the large version of that image appear? The imageChange3.html page does a similar thing, but with clicks on the thumbnails, and the big picture stays in place. Here is the code on the images in the body:

<p><img src="chimp.jpg" onclick="replaceimg('chimp.jpg')"
       alt="chimp pic" width="32" height="41" />&nbsp;
<img src="galaxy.jpg" onclick="replaceimg('galaxy.jpg')"
       alt="galaxy pic" width="32" height="41" />&nbsp;
<img src="totoro.jpg" onclick="replaceimg('totoro.jpg')"
       alt="galaxy pic" width="32" height="41" />
<p><img id="target" src="totoro.jpg" alt="totoro pic"
       width="96" height="123" /></p>

And here is the script from the end of the body of the document:

<script type="text/javascript">
     function replaceimg(path)
          var targetimg = document.getElementById('target');
          targetimg.setAttribute("src", path);

Notice that in this case the script at the end of the document is a function named replaceimg( ) which accepts a value passed to it. The value is the image file we are going to swap in for the big picture, and the value is received in the function in the variable path. In the function, the reference to the large picture (with id="target") is put into the variable targetimg. Then the setAttribute method of the targetimg object is used to set its src to be the url contained in path.


That's all well and good, but what I really wanted to be able to do was have multiple clicks on one image (or one link) toggle the image between displaying two images. Click on the picture once, and the picture changes. Click on it again, and it changes back. Click on it again, and it changes to the second image again.

I found a handy JavaScript for doing that online, and you can see the the result in the imageSwap.html page.

The code for the image itself is simple, with a call to the function swapimage():

<img src="totoro.jpg" id="totoro" onclick="swapimage();"
width="96" height="123" alt="totoro pic" />

The script (located at the end of the body of the document) is shown below:

<script type="text/javascript">

     chim = new Image(96,123)
     chim.src = 'chimp.jpg'

     tog1 = 2;

     function swapimage()  {
          switch (tog1) {
              case 1:
                  document.getElementById('totoro').src = 'totoro.jpg'
                  tog1 = 2
             case 2:
                 document.getElementById('totoro').src = chim.src
                 tog1 = 1;

The first three lines of the script get executed when the page loads (the code in the function does not execute until it is called later). The first two lines in the script preload the chimp.jpg image. The third line in the script initializes the value of the global variable tog1 to be equal to 2.

When the function swapimage() is called (triggered by a click on the image), it uses a switch command to execute either the instructions in case 1, or those in case 2. It makes this decision based on the value of the variable tog1 (which is either 1 or two). If the value is 2 (as it is the first time we click, since that how it was initialized), the routine jumps to case 2 and sets the source of the image (with id="totoro") to be the Chimp. It then also changes the value of tog1 to equal 1. The next time the function is called (triggered by the next click on the image), the routine jumps to case 1 and sets the image back to Totoro. It also sets the value of tog1 back to 2. Then it hits the break command which halts execution (so the commands below in case 2 don't get executed then). And that's how it works, back and forth.



Toggling the Display of Divs

The same concept of toggling between two images can be used to toggle any kind of element between two different states, such as making divs appear and disappear with clicks on a link. Now we are talking serious coolness, making whole sections of your Web page appear and disappear.

The toggleDiv.html page shows how I accomplished this. The page contains two divs that I want to make appear and disappear. I will do this by changing the display property of the div to none to remove the div from the display of the page, and change the display property to block to make the div appear. Both divs are preceded by links that will be used to trigger the changes.

The link toggling the display of the div with id="div1" looks like this:

<a href="javascript:;" onclick="toggleDisplay('div1');">Toggle Div 1</a>

The script (located at the end of the body of the document) that does the toggling is shown here:

<script type="text/javascript">

function toggleDisplay(obj) {
      var el = document.getElementById(obj);
      if ( el.style.display != 'none' )
            el.style.display = 'none';
            el.style.display = '';

The onclick handler script in the link calls the function toggleDisplay( ) in the script at the end of the body, passing it the id of the div it wants to toggle to display of. That id (which is received into the variable obj) is used to make the reference object el to that div. Then the routine uses an if...else conditional statement to see if the display property of the div is NOT equal to none (to see if the div is currently being displayed). If that the case, it will set the display property of the div to none so that it is removed from the display of the page. If it the case that the conditional was false (if the display property of the div is currently equal to none), the the else part of the conditional is executed, and the display property of the div is set to nothing (which means it gets its default value of block, and it appears on the page.

The other link calls the same function to toggle the display state of div2 whenever the link is clicked. The links can use the same function because they pass it the id of the div to affect.

Where this page gave me a little trouble was when I tried to make it start out with the two divs initially not displayed (with their display property set to none to begin with). It turned out that if I used CSS to set their display properties to none, then the JavaScript routine could never make them visible (I'm not sure why). So I put a script in the body of the document that sets the divs display property to none as the page is being loaded. The script to do that was simple:

<script type="text/javascript">
      document.getElementById("div1").style.display = 'none';
      document.getElementById("div2").style.display = 'none';

...but the tricky part for me was realizing that this script must be placed in the body BELOW the locations of the divs (otherwise the divs have not yet been defined when the script tries to make them disappear).


The toggleDiv2.html page shows how this same JavaScript code can be used to make an absolutely positioned sidebar div on a page appear and disappear.


Tabbed Divisions

All of the above work lead to the thought that one could have many divs that are absolutely position with CSS to appear in the same place on the Web page, and the links could be arranged as a horizontal menu (as we earlier learned to make from an unordered list of links) just above the location of the divs, and you get what looks like a set of tabbed index cards, as seen on the TabbedDivs1a.html page. Clicking on one link will make its corresponding div appear (and will also set the display of the other divs to none so that they disappear). I put borders on all side of the link rectangles except for the bottom, and they link rectangles overlap the top of the divs a little, covering the top border of the divs there, so it makes the index card effect work pretty well.

On the TabbedDivs1b.html page I tried a different method of arranging the link menu to see if I could get it to work better (version 1a turns the unordered list of links into a horizontal arrangement by making the list items inline elements; version 1b use floats to arrange the list items horizontally). Both methods worked well with enough tweaking of the CSS.

Version 1c in the TabbedDivs1c.html page is similar to version 1b except that the background color is placed on the list items (instead of the links), and the links use a white background image to block some of the background color and make the edges of the tabs look rounded. (With HTML5 you could use rounded corners instead of this graphic to make nice tabs.)

The background image on the links is shown here:   background image for rounded tabs


Once I get started on this kind of thing, I keep experimenting. In versions 2a and 2b, I added JavaScript code that would change the bottom borders of the tabs so that only the currently selected tab had no border to help enhance the tabbed index card look (actually, the currently selected tab has a border with the same color as the background color of the tab and its corresponding div). And I added CSS rollover effects to the buttons. But I think I've done enough on this.


The point is that you can create a lot of interesting and useful effects with JavaScript, and I hope you enjoyed the brief taste of the scripting language.


Where to Learn More

You can find many examples of scripts that you can use or learn from on the Web. Some of these scripts are free for you to use, while others are available for a fee (but you can learn more JavaScript techniques by studying how any of them are done). For example, a student wanting a scrolling image gallery was happy with this one we found with a quick Web search—and there are many others on that site and others. With even a partial knowledge of JavaScript, you can often modify or adapt scripts to do what you want.



Assignment - None

Because we missed some classes this semester (due to holidays) and we are down to the wire (next week is finals week, and you need to have your final project done by then), there will be no JavaScript assignment. You can use some JavaScript in your final project for extra credit.

I have left the previous assignment used in this chapter below (grayed out) in case you'd like to see what it would have been... but this is NOT a required assignment for Fall 2013.

You will be required to include examples of JavaScript in your final project. You should think about what uses of JavaScript you would like to use for your final project, and try them out on a test page (or pages) for this exercise.

Make a page (or pages) implementing three JavaScripts as discussed in today's lecture (or you can implement examples of JavaScript that you researched elsewhere).

At least one of the JavaScripts must be stored in a external file (not in the Web page).

Your Web page(s) must include text that describes what the JavaScripts used are meant to do.

Your page must validate as HTML5 using the validator at: http://validator.w3.org/

Your CSS must validate using the validator at: http://jigsaw.w3.org/css-validator/

Send an email to tbeach@unm.edu that includes the URL to your main page for this assignment.

NOTE! The Subject line of this email should be "IT145 YourName Asg. 12"

You will be graded on:

Your JavaScripts must work correctly.
How well you followed directions
You sent the correct URL in your email.
The page validates using the validators listed above.




See final day page for notes about the final project.