Marketing for Libraries Logo

Dynamic Websites Section: Interactivity

Much of the interactive available using HTML5 comes from the use of JavaScripts.

JavaScript is an easy-to-use scripting language based on an object-oriented programming philosophy. In other words, it's designed in easy-to-copy "chunks" of code. The code is written directly into the HTML page. It is a client-side scripting language, so you don't need any special software installed on your web server for the scripts to work.

Scripts are a set of directions to a computer. JavaScript and VBScript are two of the most common scripting languages in use today. A program such as a web browser translates the text script into computer commands.

Java and JavaScript are totally different languages.

Java is a compiled language developed by Sun. Java is written and then packaged into a self-executing file. To create an application with a compiled language, you typically need a special programming tool or development environment.

Originally developed by Netscape for server side scripting, JavaScript is an object-oriented scripting language. With JavaScript, you can write a script with a text editor (Notepad, SimpleText, etc.). A script is just plain ASCII text.

JavaScript is great for adding interactivity to your page. Although most browsers support JavaScript, some programmers avoid them because they can cause problems with some browsers. Rather than just using JavaScripts for fun, think about useful applications that really contribute to the quality of your page rather than silly uses that may interfere with page operation. For example, a rollover button is nice because users can see that their mouse is in the correct location. A question and answer button with a pop-up window is nice for practice tests.

try it Try It!
Go to Javascript Basics.
Explore some examples of Javascripts in action.

Widgets are often written in JavaScript.

readRead!
West, Jessamyn (January 2010). What is the what with widgets? Computers in Libraries, 42-43.

The Basics

JavaScript can make your website more interactive and dynamic. The scripts are set to execute when something happens such as when the mouse moves over a button. They can even change the content of an HTML element.

Read JavaScript - General Introduction for some background information.

JavaScript Lingo

Here's some technical language that might be useful as your learning JavaScript basics.

 

Script and Nonscript Tags

JavaScripts can be used to make your website more dynamic and interactive.

The <script> tag is used to define the client-side script. The script element may contain scripting code or point to an external script file using the src attribute.

Scripts may appear in the <head> or <body> of your document. Sometimes they appear in both places, so if you're examining a web page look in both places.

Examine the following sample code.

<script>
document.write("This text will appear on the screen.")
</script>

Not all browsers support particular scripts. The <noscript> tag is used to provide alternative content for browsers that don't support scripts or screen readers that can't handle the scripts.

Examine the following sample code.

<script>
document.write("This text will appear on the screen.")
</script>
<noscript>Sorry, your browser does not support this script.</noscript

try itTry It!
Go to w3schools and read about Scripts.
Use the Try It Yourself buttons to practice coding.

When using a JavaScript you need to declare in your head area that you will be using this language. This is also the area where you use meta tags to declare other information. Add a language declaration like the one below:

<meta name="author" content="Annette Lamb" />
<meta name="keywords" content="pet, dog, puppy, cat, kitten, fish" />
<meta name="description" content="Choosing a pet." />
<meta name="copyright" content="&copy; 2013 Annette Lamb" /> 
<meta http-equiv=”Content-Script-Type” content=”text/javascript” /> 

Elements of JavaScript

JavaScript contains several elements. These are discussed below.

Many times javascripts have conditions and use an if, else approach using confirm( ) to check for a true or false statement based on user input. Be sure you notice the difference between the ( ) and the { } symbols. Try the following conditional javascript. Let's save it as practice2.html

<script language="Javascript" type="text/javascript">
if (confirm("Click OK if you love animals.")) {
alert("Great! Let's find the perfect pet for you!")
}
else {
alert("A pet rock would be a good choice for you.")
}
</script>

 

JavaScript Events

There are endless possibilities for Javascripts.

JavaScript events are actions that course interactivity on your page such as clicking a button or rolling your mouse over an image.

Examine the following sample code from w3schools. Notice that there's a script in the <head> area and also code in the <body>. This script displays a button. When clicked, the button displays the date and time. To try this script, go to Acting on the onclick event.

<head>
<script>
function displayDate()
{
document.getElementById("demo").innerHTML=Date();
}
</script>
</head>

<body>
<h1>My First JavaScript</h1>
<p id="demo">This is a paragraph.</p>
<button type="button" onclick="displayDate()">Display Date</button>
</body>

Examine the following sample code from w3schools. Notice that there's a script in the <head> area and also code in the <body>. This script displays an image. When the mouse rolls over different areas of the image, text is placed on the screen. To try this script, go to Acting on the onmouseover event.

<head>
<script>
function writeText(txt)
{
document.getElementById("desc").innerHTML=txt;
}
</script>
</head>

<body>
<img src ="planets.gif" width ="145" height ="126" alt="Planets" usemap="#planetmap" />

<map name="planetmap">
<area shape ="rect" coords ="0,0,82,126"
onmouseover="writeText('The Sun and the gas giant planets like Jupiter are by far the largest objects in our Solar System.')"
href ="sun.htm" target ="_blank" alt="Sun" />

<area shape ="circle" coords ="90,58,3"
onmouseover="writeText('The planet Mercury is very difficult to study from the Earth because it is always so close to the Sun.')"
href ="mercur.htm" target ="_blank" alt="Mercury" />

<area shape ="circle" coords ="124,58,8"
onmouseover="writeText('Until the 1960s, Venus was often considered a twin sister to the Earth because Venus is the nearest planet to us, and because the two planets seem to share many characteristics.')"
href ="venus.htm" target ="_blank" alt="Venus" />
</map>

<p id="desc">Mouse over the sun and the planets and see the different descriptions.</p>

</body>

try itTry It!
Go to w3schools and read about JavaScript Tutorial.
Use the Try It Yourself buttons to practice coding.

Work your way through the Javascript examples. This page provides many great examples.

Try It!

Check out the following fun scripts. Give them a try!

Navigation

This navigation script will let you go back one page. It's like clicking the back button on your browser. This is useful when people are coming from different places and need to go back to different places. Go to Rocks for an example.

<a href="javascript:history.go(-1)">Go back </a>

Popups

Popups can be useful for news or instructional materials. For example, you might use a pop-up for definitions, help, or additional information. The problem with popups is that some people have turned off their pop-up options in their browser.

Go to popup.html for an example. Go to Rock Popup for an example.

<head> <script type="text/javascript">
window.open('annoy.html','popup','width=250,height=250');
</script> </head>

Rollovers

Rollovers occur when a user rolls the cursor over an object such as a graphic and triggers an action such as a change in a graphic.

Go to bugs.html for an example of a simple blank to graphic rollover.

What Else Do I Need To Know?

If you decide to include Javascripts in your website, use care. They don't work with all browsers, so be sure you test your scripts on different computer platforms and browsers.

JavaScripts are case sensitive, so copy and modify scripts carefully.

If you want to test your skills try the JavaScript Quiz Test.

 

The Language of JavaScript

JavaScript contains several elements. These are discussed below.

OBJECTS

Objects are building blocks of the script. JavaScript contains pre-defined objects, and you can create your own.

window.document.mystuff

An object can have properties (sort of like adjectives)

For example, an object might have a name, a size, and a text value.

window.name ("namegoeshere");

An object can have methods (sort of like verbs)

For example, an object might be able to display a text message, record information, or create an alert box.

document.write ("Hello!");

sample 1 A document last modified script (using HTML presentation: <i>).

sample 2 A document last modified script (using an inline style).

sample 3 A document last modified script (using an internal stylesheet).

sample 4 An external script that writes a footer.

sample 5 An external script that writes a footer and a header at the same time using styles.

sample 6 You can even insert an image by writing the correct code.

sample 7 Another example of writing an image to a page.

sample 8 You can open a window with a method in the <head> section.

sample 9 You can open an alert box with a method in the <head> section.

FUNCTIONS

Functions combine a series of statements under one name and perform an action. They are usually placed in the <head> section.

sample 1 This function loads with the page but is called with an onload event handler in the <body> tag.

sample 2 After you click on the link to go to this page, a function loads with the page and is written immediately with a document.writeln method that is also in the <head> section.

sample 3 The functions in the <head> are called by the event handlers in the anchor tags to make a simple rollover

sample 4 The functions in the <head> are called by the event handlers in the anchor tags; text is written to the status bar.

OPERATORS

Operators can assign, compare, compute, and evaluate values. Operators combined with objects and variables form expressions.

== (equals), && (and), != (does not equal), || (or), -- (decrement), ! (not), + + (increment), = (simple assignment), etc.

sample 1 This time-of-day greeting depends on a simple operator.

sample 2 This form verification script is a simple example of using operators.

VARIABLES

Variables are containers that hold data. The current value in a variable can be calculated, output, passed along to other variables, etc. You can declare a variable at the beginning of a page and use it throughout the document, or you can declare a variable at the beginning of a function for just that particular function.

sample 1 Notice the variables used to create a simple password verification (username=iupui, password=L571 OR L526).

ARRAYS

An array is a set of variables that are saved under the same name.

sample 1 Two arrays are created to hold the info for the days of the week and the months of the year.

EVENT HANDLERS

Events and event handlers respond to certain events (from the user/browser).

sample 1 This onclick event handler is placed directly in the form itself to open a window.

sample 2 This onmouseover even handler is placed directly in the anchor tag.

sample 3 Another example of making a simple rollover effect here with onmouseover and onmouseout within the anchor tag.

Examples

Other examples for you to adapt:

sample 1 Here is a simple way to make a drop-down menu — and the nice thing about this script is that you can use several (with slight modification) on the same page.

sample 2 Here is a drop-down menu that uses a function called by the onclick event handler.

sample 3 The pop-up windows are defined by a function before they are called with an event handler.

sample 4 Here is how you can close a window that you have opened.

sample 5 You can redirect your user to a different page depending on the user's browser.

sample 6 Use JavaScript to write anything that you want to your document — but if your page depends on that script to work, you must provide an alternate for users who have disabled JavaScript in their browsers. (Do you know how to disable JavaScript in your browser?)

Samples created by Krystal McReynolds. Edited by Annette Lamb.

External Scripts

Sometimes you want to run the same script on many pages. In this case, you'll write a JavaScript as an external file. Then, simply call the .js file when you need it. It's similar to the way you "call" your CSS file. You use the <script> start and end tags within the HTML document to call this .js file. Like CSS, you DO NOT include the <script> tag in an external JavaScript.

Check out examples at Landmarks JavaScript.

Example

Footers are a good use of an external javascript. You'd put the following script in your HTML document.

<script src="footer.js"></script>

Then, create the JavaScript file in Dreamweaver or a text editor. Simply save the document with the .js file extension. For an example, go to footer1.js to see the example below:

document.write("All Rights Reserved. Copyright 2006.");

You can add some text and today's date. For an example, go to footer2.js.

var today = new Date(); 
document.write('Based on the Internet clock ' + today.toLocaleString() );

You can also add a graphic in addition to text. For an example, go to footer3.js.

document.write("<img src='logo.jpg'> Enjoy this student-produced page.");

Repurposing Scripts

You're probably thinking this is a lot of work. The key for beginners is re-purposing scripts rather than building your own from scratch. In other words. Let's change this Eating Right script into a script that can be used with the pets project or the landmarks project. Then, save it as practice3.html

To repurpose a script:

Many websites contain code you can adapt for your own use. This is called repurposing. If you copy any code be sure to give credit to the source of the code. You can do this as a comment in your HTML code.

Before you add a JavaScript to your HTML, decide whether it should be placed in the body section and/or the head section. Scripts placed in the body section will be executed while the page loads, while scripts in the head section will be executed when called.

Before you copy a JavaScript, look for any restrictions on use. Some websites ask for users to include a link back to the developer's website. Others request that you leave any comments in the code.

You don't need to create JavaScripts from scratch. It's easy to copy a script and repurpose it for your need. Go to the page containing a JavaScript you like. Then, view the Source. Look in both the head and body for scripts. Be sure to copy everything within the script tags. <script> </script>

Many times you don't need to make any changes. If you wish to make a change, be sure to only change parts of the code you understand. For example, if you open the Alert Box page. It displays an alert box as the page loads. You might want to change the message that is displayed in the alert box. Below, I changed the "Welcome to my Web Site" message to "This page is still under construction!".

Copied Script

<script type="text/javascript">
alert('Welcome to my Web Site!');
</script>

Modifed Script

<script type="text/javascript">
alert('This page is still under construction!');
</script>

JavaScripts To Repurpose

Let's examine some JavaScripts you can repurpose.

Passwords

In many environments you may wish to use a simple password system. Check out:

Try the Video page. Notice that it asked for the password. Use the word video to try it out. Then, view the source of the blank password.html page.

Pulldown Menu

Go to Landmark Pulldown Menu to see an example of JavaScript for a pulldown menu.

Slide Show & Virtual Tours

Slide Show with Text. There are many JavaScripts for slide shows. Go to Landmarks Gallery to see a slide show.

Virtual Field Trip with Controls. Here's another way to provide a virtual tour. Visit St. Peter's Church. Let's repurpose this one by copying the JavaScript from the head and the form from the body. Then, simply change the .jpg file names and descriptions. Go to Landmarks Gallery 2 to see the script repurposed.

Slide Show. Here's a third option for a slide show. Go to Landmarks Gallery 3 and view the script.

Tools

JavaScripts can be used to embed tools such as calendars and calculators on your page. Check out:

Try copying the JavaScript from the head and the body and creating your own project. Be sure to give credit! Check out Field Trip Fun as an example.

Tutorials

There are many websites that use JavaScripts to help students learn.

Go to Animal Homes. Think about how you coud modify a school to meet your needs.

You'll want to modify the SCRIPT at the top of the page in the head area by indicating your "correct items" ('a','b','c','d') and the appropriate link page (correct.html or incorrect.html). Also add a note thanking the code developer.

<SCRIPT LANGUAGE="Javascript">
<!--Hide from older browsers.
This code was adapted from Be an Architect page at 
http://www.sanford-artedventures.com/play/arch2/a2.html

function check(){
r=new Array('a','b','c','d');
for(i=0;i<r.length;i++){
el = document.theForm.elements['q'+i];
if(r[i]!=el.options[el.selectedIndex].value){
location.href='wrong.html';
return;
}
}
location.href='right.html';
}
function MM_openBrWindow(theURL,winName,features) { //v2.0
window.open(theURL,winName,features);
}
//-->
</script>

Scroll down the code to locate the FORM used for the questions. Notice the values assigned to each possible answer. These values can be changed to meet your needs. We have 4 questions, but you could increase this number by adding "q4", "q5", etc. Be sure to add the "correct answer" to the SCRIPT if you add additional items.

<FORM NAME="theForm" onSubmit="check(); return false;">
<table width="440" border="0" cellpadding="3">
<tr align="center"> <td><img src="hole.jpg" alt="hole"></td>
<td><img src="water.jpg" alt="water"></td>
</tr> <tr align="center"> 
<td><select name="q0">
<option value="0">This is a home for a </option>
<option value="a">skunk.</option>
<option value="b">fish.</option>
<option value="c">bird.</option>
<option value="d">bear.</option></select>
</td>
<td><select name="q1">
<option value="0">This is a home for a </option>
<option value="a">skunk.</option>
<option value="b">fish.</option>
<option value="c">bird.</option>
<option value="d">bear.</option></select></td></tr>
<tr align="center"> <td><img src="nest.jpg" alt="nest" ></td>
<td><img src="cave.jpg" alt="cave" ></td></tr>
<tr align="center">
<td><select name="q2">
<option value="0">This is a home for a </option>
<option value="a">skunk.</option>
<option value="b">fish.</option>
<option value="c">bird.</option>
<option value="d">bear.</option></select></td>
<td><select name="q3">
<option value="0">This is a home for a </option>
<option value="a">skunk.</option>
<option value="b">fish.</option>
<option value="c">bird.</option>
<option value="d">bear.</option></select></td></tr>
<tr> <td colspan="2" align="center"> 
<INPUT TYPE="button" VALUE="Am I right?" onClick="check()">
</td>
</tr>
</table>
</form>

 

JavaScript with Dreamweaver

If you've got Dreamweaver, you don't need to know anything about JavaScripts to use them for simple applications. Let's start with some of the automated options available in Dreamweaver. Then, you can adapt these scripts for other purposes.

Rollovers

Create simple rollovers using the following menus and options - Insert>Image Objects>Rollover Image in Dreamweaver.

Go to Minerals in Food for an example of using Dreamweaver JavaScripts for simple rollovers in a tutorial. Notice that the directions are in italics.

Go to Rocks in Our World for an example of using rollovers to check answers.

To build your own interactive page using photos and correct/incorrect answer graphics:

Adapt Rollovers

You may not get exactly the results you wish using the standard Dreamweaver options. For example, you might want students to click on the photo rather than roll over the photo. You'll need to edit the JavaScript, however you don't need to know everything about JavaScript to make a small change.

To change your mouse rollovers to mouseclicks:

Navigation Bars

Another JavaScript that comes with Dreamweaver is the navigation bar option. You'll need to create buttons in Fireworks or use buttons you find online. If you want them to look interesting, you'll have three different versions of your buttons: mouseup, mouseover, and mousedown.

To add a navigation bar to your Landmarks project:

HTML5 Drag and Drop

One of the coolest features of HTML5 is the "drag and drop" option. You grab an object and drag it to a different location.

Although the coding looks complicated, it's actually easy to adapt for any purpose.

Here's an example. Notice that the <script> is placed in the <head> area. There's also code in the body of the document.

Examine the following sample code.

<!DOCTYPE HTML>
<html>
<head>
<script>
function allowDrop(ev)
{
ev.preventDefault();
}

function drag(ev)
{
ev.dataTransfer.setData("Text",ev.target.id);
}

function drop(ev)
{
ev.preventDefault();
var data=ev.dataTransfer.getData("Text");
ev.target.appendChild(document.getElementById(data));
}
</script>
</head>
<body>

<div id="div1" ondrop="drop(event)"
ondragover="allowDrop(event)"></div>

<img id="drag1" src="img_logo.gif" draggable="true"
ondragstart="drag(event)" width="336" height="69">

</body>
</html>

Check out the Hieroglyphics example. Try repurposing this code.

try itTry It!
Go to w3schools DRAG AND DROP page. Read about the options. Then, try adapting a script to fit your needs using their Try It Yourself area.

 

Resources

The easiest way to learn JavaScript is to by exploring existing resources and adapting scripts. Use the following resources for your exploration.

JavaScript Sources

JavaScript Tutorials

Website for Articles

Websites for Books

JavaScript Testing

Learn More

Free JavaScript Resource - If you can overlook all the advertising, there are some good links here.

 


| eduscapes | IUPUI Online Courses | Teacher Tap | 42explore | About Us | Contact Us | © 2006-2013 Annette Lamb & Larry Johnson