Larger Text Normal Text Smaller Text

IT 180 Web Development I, Fall 2009

 

Lesson 16: External JavaScript Files; Events

Using external JavaScript files

JavaScript programs can be stored in a separate file and then included in the HTML document that needs to use them.

This way they can be reused without retyping, much like the style rules in an external stylesheet file.

The external file should have the extension .js.

It is incorporated into the document with a SRC attribute in the <script> tag.

    <script> type="text/javascript"  src="URL of the file"> </script>

Warning:There should NOT be any JavaScript statements inside the <script> </script> container.

If there are, they will be ignored; they will not be executed.

Example: Using an external JavaScript file

Suppose the following script is stored in a file named hello.js

    // JavaScript greeting revisited
    // ONLY this JavaScript is is the file.
    // NOT the <script> tags or other HTML
    
    var visitor = prompt("What's your name.");
    document.write("This page dedicated to " + visitor);

Then it can be incorporated into a document with:

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

The result will be the same as if the document had been

      <script type="text/javascript" >
      <!--
        var visitor = prompt("What's your name.");
        document.write("This page dedicated to " + visitor);
      // -->
      </script>

Here is the complete example.

Image Sources

So far the only parts of a web page that we have changed after the document is loaded have been the values of textboxes and textareas.

Using JavaScript, it is also possible to change an image that is displayed.

An image is included in a web document with the <img> tag.

        <img src="your image source URL" alt="your alt text" />

for example,

        <img src="que.jpg" alt="" />

The "src" attribute determines what image is displayed.

To change the image, we can change the url assigned to its src, much the way we change the value assigned to a textbox.

Identifying an image

All images in a Web page are grouped under the object named images.

The name images is used immediately after document to indicate all the images: document.images.

To refer to a specific image, it must have an id attribute.

           <img src="image_source_URL" 
                alt="alternate text"
                id="specific_image_name"  />

Then it is referred to in JavaScript as document.images.specific_image_id.

Example 2: Changing an image src

For example, the image below has id "quest".

You can specify it in a JavaScript statement as document.images.quest.

The button changes the src with the onclick event handler:

          <img src="que.jpg"  id="quest" alt="" />

    

       
              
      <input type="button" 
              value="click me"               
              onclick=" document.images.quest.src='smile.jpg'; "

Here is the complete example.

Example 3: Changing images

In this example, three different buttons change the same image.


   <img src="que.jpg" id="quest1">
       <input type="button"
              value="???"
              onclick="document.images.quest1.src='que.jpg'">
       <input type="button"
              value="SMILE!"
              onclick="document.images.quest1.src='smile.jpg'">
       <input type="button"
              value="frown"
              onclick="document.images.quest1.src='frown.jpg'">

Here is the complete example.

An image swapper function

It can be tedious to use document.images.imagename.src every time.

Here is another way - it uses a function named swap_pic.

Unlike the Math library of functions, this one did not come with JavaScript in a standard library.

Instead, the swap_pic function is stored in the external javascript file at http://wyrd.hood.edu/~echang/it180/fall07/lib/library_180.js

The function has two arguments.

The first should be the id of the image.

The second should be the URL of the new source.

Example 4: Using swap_pic()


   

    
<!-- Include the library --> <script type="text/javascript" src="http://wyrd.hood.edu/~echang/it180/fall07/lib/library_180.js"> </script> <!-- Use the swap_pic() function from the library --> <img src="que.jpg" id="quest2" alt="" /> <input type="button" value="click me" onclick=" swap_pic('quest2', 'smile.jpg')">

Here is the complete example.

Example 5: Playing with image swapping

Here are two different images and four buttons that act on the images.


 




The HTML:

Each onclick event calls the same function, telling it both the image ID and the url of the new source.


<img id="discs" src="bluedisc.gif" alt="" />

<img id="blocks" src="redblock.gif" alt="" />

  <input type="button"
         name="first"
         value="Change disc to red"
         onclick="swap_pic('discs', 'reddisc.gif');"/><br/>
         
  <input type="button"
         name="second"
         value="Change disc to yellow"
         onclick="swap_pic('discs', 'yeldisc.gif');"/><br/>
         
  <input type="button"
         name="third"
         value="Change block to blue"
         onclick="swap_pic('blocks', 'blueblock.gif');"/><br/>
         
  <input type="button"
         name="fourth"
         value="Change block to yellow"
         onclick="swap_pic('blocks', 'yelblock.gif');"/><br/>


Here is the complete example.

Example 6:

Using the function may not seem any simpler than writing out the assignment statement, but it can be more versatile.

Also, the function name is a reminder of what is being done.

Enter the name of the image you want:

       <script type="text/javascript"   
                src="http://wyrd.hood.edu/~echang/it180/fall07/lib/library_180.js">
       </script>
 
 
   <img src="reddisc.gif" id="quest3" alt="" />

<form name=frmPic action="">

   Enter the name of the image you want (que, smile, or frown):
    <input type="text" 
           name=txtPicname
           value="que, smile, or frown" />
   
    
   <input type="button"
             value="Change it"
             onclick="
                     var picname = document.frmPic.txtPicname.value + '.jpg';
                     swap_pic('quest3', picname);            
                     ">
</form>

Here is the complete example.

Other events

So far all our programs have either been scripts that are executed when the page is loaded, or handlers for the onclick event for a button.

There are several other types of events that apply to certain objects in a document. Some of them are:

Event       Occurs when...                                 Atribute name 
click       User clicks on element                         onclick
change      User changes value of textbox or textarea      onchange
focus       User moves focus to form element or link       onfocus
blur        User removes focus from form element or link   onblur
mouseover   User moves mouse pointer over an element       onmouseover
mouseout    User moves mouse pointer away from an element  onmouseout
load        User loads the page in the browser             onload
unload      User exits the page                            onunload

Example 7: onmouseover and onmouseout

Here is an example that shows handling mousever, mouseout and onclick events.

With the most recent browsers (Firefox 1, IE 6, and later), the attributes and events will work with most elements.

Older browsers may require that the element be an anchor with an href attribute value.

GO OVER AND OUT and click this line!

The xhtml is:

        <img src="que.jpg" id="quest4" />

        <p onmouseover="swap_pic('quest4', 'frown.jpg');"   
              onmouseout="swap_pic('quest4', 'smile.jpg');"   
              onclick="swap_pic('quest4', 'que.jpg');" >
             
            GO OVER AND OUT and click this line!
        </p>

Here is the complete example.

If this case, the event handler is in the <p> tag because teh paragraph is the element that contains the text. If you use an image, the event handler can be in the image tag.

The example uses the same swap_pic function as before. The function is in an external library; the event handler calls it with a different ID.

 
Comments to: chang@hood.edu
Last Modified: 06 November 2007. 19:51

 

Hood College Department of Computer Science: Course materials © 1997-2007 by Elizabeth Chang.


 
Valid CSS! Valid XHTML 1.0!