JavaScript

< Back to Tutorials

Summary

JavaScript is a programming language that you can use in HTML pages to add features to your site.

Experience Needed
  • Basic understanding of HTML
Software
  • Any text editor, such as NotePad
  • A Web browser
Description
Create an image rollover
Skills / Concepts Covered
  • attributes
  • events

One of the easiest things you can do with JavaScript is called a 'rollover effect'. You can make something happen when the user rolls the mouse over an image or text.

The most basic rollover effect simply requires that you add an 'onmouseover' attribute to an <img> tag:

This code:

<img src="greencircle.gif" onmouseover="this.src='redcircle.gif'">

Produces the rollover effect below.

See what happens when you move your mouse over the green circle.

The code above tells the browser that there is an image with the source (src attribute) set to "greencircle.gif". The second attribute onmouseover tells the browser to set the source (src) of this image ('this') to 'redcircle.gif".

Something to keep in mind is the nested quotes. The file names are inside of single quotes, while the value of the 'onmouseover' attribute is all inside of double quotes. You can use either single- or double-quotes around value names in HTML tags, but you need to be consistent and close every quote you open. This is one of the most common mistakes in JavaScript and HTML.

Notice how the image does not change back when you remove the mouse. To do that we need to add more script to our img tag.

This code:

<img src="greencircle.gif" onmouseover="this.src='redcircle.gif'" onmouseout="this.src='greencircle.gif'">

Produces the rollover effect below.

Here we've just added an onmouseout attribute, telling the browser to set the source (src) of this image (this) back to the green circle image.

It's convenient to use the 'this' keyword, but sometimes we want to explicitly state the identity of the image.

This code:

<img src="greencircle.gif" name="green" onmouseover="green.src='redcircle.gif'"onmouseout="green.src='greencircle.gif'">

Produces the rollover effect below.

Here we've given the image a name, using the name attribute. Now in the JavaScript we use the syntax 'green.src' instead of 'this.src'.

It has the same effect as before, but the advantage is if you want to have the rollover affect a different image.

This code:

<img src="greencircle.gif" onmouseover="blue.src='redcircle.gif'" onmouseout="blue.src='bluecircle.gif'"> <img src="bluecircle.gif" name="blue">

Produces the rollover effect below.

Here the blue circle image is given the name 'blue' and the JavaScript in the img tag of the green circle image controls it.

You can do lots of other things with a rollover effect. A common use is to have navigation buttons change when a user rolls over them.

This code:

<a href="home.html'>
<img src="button_home.gif" onmouseover="this.src='button_home_over.gif'" onmouseout="this.src='button_home.gif'">
</a>
<br />
<a href="about.html'>
<img src="button_about.gif"onmouseover="this.src='button_about_over.gif'" onmouseout="this.src='button_about.gif'">
</a>

Produces the rollover effect below.


More Resources

http://www.webreference.com/js/column1/
http://www.joemaller.com/js-singleroll.shtml
http://www.outfront.net/tutorials_02/adv_tech/rollovers1.htm


Writing to the Screen
Skills / Concepts Covered
  • Writing to the Web page
  • Variables

The rollover effects above were written 'inline', that is, inside of HTML tags. Here, we use the <script> and </script> tags to tell the browser to do something.

Note the semicolon (';'). This tells the browser that we're at the end of a line. In JavaScript, using the semicolon to indicate the end of a line is usually optional. However, in other languages it is required, so using semicolons to mark the end of a line is a good programming habit for you to develop.

This code: 'document.write();' tells the browser to write something. For example, we can tell the JavaScript to write the word, "Hello!"

This code: Looks like:
<script>
document.write("Hello!");
</script>

We can also include dynamic information

This code:Looks like:
<script>
var answer = 1234 * 5678;
document.write("1234 * 5678 = " + answer);
</script>

In the script above, we create a 'variable' which has a value calculated by the browser.

We use quotes ('"') around the text that we want to display, and use the plus sign ('+') to tell the browser to show the value of the variable named 'answer'.

Another way to use JavaScript to write text to the screen is with the 'alert' function.

<script>
var message = "Hello! Welcome to my Web page!";
alert(message);
</script>

Try placing the above script in a Web page and see what happens.

You can also trigger the alert from a rollover, or when the user clicks something.

This code:Looks like:
<form name='test_form'> Your name: <input type='text' name='name'> <br /> <a href="#' onclick="alert('Your name is: ' + document.test_form.name.value); return false;">click</a>
Your name:
click

The above code is HTML for creating a form, with a single text-entry box and a link. Clicking the link calls the 'alert' function, which then accesses the value of 'name', which is whatever you've typed into the text box. It then pops up the alert and prints the value.

More Resources

http://www.mediacollege.com/internet/javascript/basic/document-write.html
http://ncthakur.itgo.com/js03.htm
http://www.tizag.com/javascriptT/javascriptalert.php


Displaying a Random Image
Skills / Concepts Covered
  • Math Functions
  • 'if' Conditions

Something fun you can do with JavaScript is to place images on your page using random numbers.

This code:Looks like:
<script>
var random_number = Math.random();
if (random_number > 0.5) {
      document.write("<img src="greencircle.gif" alt='" + random_number +'>")
} else {
      document.write("<img src="redcircle.gif" alt='" + random_number +'>")
}
</script>

Reload this page a few times. You should see the image change.

In the script above, the first line creates a variable named 'random_number' and assigns it a value using one of the built-in math functions, in this case, 'Math.random()'. Math.random() creates a number between zero and one. We then use a condition using the keyword 'if' followed by a statement in parentheses.

If the statement is true, the command within the curly braces ('{' and '}') is carried out. Otherwise the command following the 'else' keyword is caried out. In both cases, the random number is assigned to the 'alt' attribute of the <img> tag If you view the source of this page you will see the random number that was used to determine which image to display.

More Resources

http://www.w3schools.com/js/tryit.asp?filename=tryjs_randomlink
http://www.javascript-page.com/ranimage.html


Display the Current Time and Date
Skills / Concepts Covered
  • Arrays
  • if/else if conditions

You can use JavaScript to display the time and date on your Web page.

This code:Looks like:
<script>
document.write(new Date());
</script>

Instead of writing a word, we use the code "new Date()" which tells the browser to create a new 'object' that includes the date and time, as you can see above. The browser looks at the time and date on the computer on which it's running, so the date and time should always be local to whomever is looking at it.

The date above is long and awkward, however. Fortunately there are ways to format the output to get something better.

This code:Looks like:
<script>
var newDate = new Date();
document.write(" The day of the week is: " + newDate.getDay());
document.write(" The day of the month is: " + newDate.getDate());
document.write(" The month is: " + newDate.getMonth());
document.write(" The year is: " + newDate.getYear());
document.write(" The hour is: " + newDate.getHours());
document.write(" The minute is: " + newDate.getMinutes());
document.write(" The second is: " + newDate.getSeconds());
</script>

The variable 'newDate' actually includes lots of values. We can get the day of the week, the month of the year, etc. However, all the information is handled as numbers, where Sunday is 0, Monday is 1, Tuesday is 2, etc.

We can use this number to write a message to the screen based on the time

This code:Looks like:
<script type="text/javascript">
var newDate = new Date();
var newTime = newDate.getHours();
if (newTime < 12) {
      document.write("<b>Good morning</b>")
} else if (newTime > 18) {
      document.write("<b>Good evening</b>")
} else {
      document.write("<b>Good afternoon</b>")
}
</script>

The if statement above does a simple check to see if the value of 'newTime' is less than 12. If so, the script prints out "Good morning". The condition includes two 'else' clauses, so if the first condition fails (if 'newTime' is not less than 12) the second condition is tried, and so on. The last else statement is a 'catch-all' in that if none of the above conditions are met, then the script will perform the final action, in this case, if the time is not before 12 and not after 18 (6pm) then it must be the afternoon.

Treating all date information as numbers is only somewhat useful. It's often more helpful to have the names of days and months. We can do this by creating 'arrays'. An array is a variable with more than one value. We tell the browser which value to use by using square brackets ('[' and ']') after the array name.

An important note is that arrays start counting at zero (0) not one (1), so the first value in an array is really the 'zero-th' value.

This code:Looks like:
<script>
var newDate = new Date();
var weeks = new Array();
weeks = ["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"];
document.write(" The 'zero-th' day of the week is " + weeks[0]);
document.write(" The first day of the week is " + weeks[1]);
document.write(" The second day of the week is " + weeks[2]);
document.write("<br />");
document.write(" Today's number is " + newDate.getDay());
document.write(" Today is " + weeks[newDate.getDay()]);
</script>

The code above has an array for the days of the week, starting with Sunday = 0. Using 'document.write' we print the 'zero-th' value of the array, Sunday. We print out value number 1 and 2 of the array, and get 'Monday' and 'Tuesday'. We can get the current day of the week with the code: 'newDate.getDay'. When we use that value when selecting a value from the array, we get today's day of the week.

We can also create an array for the months of the year

This code:Looks like:
<script>
var newDate = new Date();
var weeks = new Array();
weeks = ["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"];
var months = new Array();
months = ["January","February","March","April","May","June","July",
    "August","September","October","November","December"];
document.write(" Today is " + weeks[newDate.getDay()] +
    ", " + months[newDate.getMonth()] + " " + newDate.getDate());
</script>

One important point is that not all browsers handle the Date() function the same way. Specifically, when returning the year with '.getYear', some browsers give the correct year, but other browsers, such as Firefox, give the number of years since 1900, so 2007 would appear as '107'. We can use more JavaScript to fix that.

This code:Looks like:
<script>
var newDate = new Date();
var weeks = new Array();
weeks = ["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"];
var months = new Array();
months = ["January","February","March","April","May","June","July",
    "August","September","October","November","December"];
var year = newDate.getYear();
if (year < 2000) {
      year += 1900;
}
document.write(" Today is " + weeks[newDate.getDay()] +
    ", " + months[newDate.getMonth()] + " " + newDate.getDate() + ", " + year);
</script>

In the script above, we create a variable named year, and set its value by using the '.getYear' function. We then use a condition, 'if (year is less than 2000)' to find out whether the variable year is a real year, or a number such as '107'. If it is a small number, we simply add '1900' to the value to make it a proper year. The syntax '+=' means add whatever is on the right to the variable on the left, in this case, 'year'.

More Resources

http://www.codeave.com/javascript/code.asp?u_log=7025
http://www.w3schools.com/js/js_obj_date.asp
http://www.w3schools.com/js/tryit.asp?filename=tryjs_timing_clock


Automatically Redirecting the Browser to a New Page
Skills / Concepts Covered
  • Functions
  • Comments

Web pages often change, and you will sometimes want to redirect users to a new page from one that is obsolete. You could simply delete the old page, but there may be links on other sites that still point to it, so you need a redirect.

<script>
window.location = "http://www.myglife.org/";
</script>

Copy and paste the code above into a Web page, then view the page in a browser. As soon as the page opens, it redirects to myglife.org

Another way to do the same thing is to use the syntax, 'location.replace()'.

<script>
location.replace("http://www.myglife.org/");
</script>

You can delay the redirect in order to give people time to read any text you have on the page.

<script>
<!--
// create a function that performs the redirection
function redirect(){
      window.location = "http://www.myglife.org/";
}
//-->
</script>
<!-- call the setTimeout() function to delay the call to the redirect() function -->
<body onLoad="setTimeout('redirect()', 10000)">
<h4>This page has moved. Please update your links. You will be redirected to the new page in 10 seconds</h4>

Most of the scripts in the earclier examples were placed in the middle of the Web page. It is usually a good idea to place JavaScript code between the <head> and </head> tags to prevent the code from diaplying in older browsers.

<head>
<script>
<--
// Your code goes here
//-->
</script>
</head>

This code: '<--' is an HTML comment, telling the browser not to display the JavaScript code that follows.
This code: '//' is a JavaScript comment, telling the browser that the line should be ignored. It's often handy to add comments to your scripts to help you remember what the code is supposed to do.
This code: '//-->' is a JavaScript comment next to the end of the HTML comment. This tells the browser to ignore the comment itself.

More Resources

http://javascript.internet.com/navigation/dynamic-timed-redirect.html
http://www.web-source.net/javascript_redirect2.htm
http://www.tizag.com/javascriptT/javascriptredirect.php