IT581: Practicum in Web Development, Summer 2015 (Hybrid)

Write JavaScript Functions

JavaScript function

Trying to type a complete JavaScript event handler program as the onclick attribute value is awkward.

It seems as if an attribute value in an HTML tag should be something short.

What we need is a way to place most of the JavaScript code elsewhere so that in the onclick value we can just say where to find it.

The solution is to make user-defined functions - functions that are created by the programmer rather than provided by the language.

The use of the term "user" may seem odd, because we commonly refer to the user/viewer of the program/page that way.

In this case it means the user of the programming language--the programmer.


Defining a function

To define a new function, you must first specify its name

If there are any inputs (arguments), you must specify what they are to be.

If it is to send back a return value, You must also tell what that value will be and how it will determine that result.

Some functions are designed to perform a task without returning any value.

Such a function is sometimes referred to as a procedure, but it is still defined with the word function.


Syntax of a function definition

A function definition


Example of a function

    function greet() 
    {
        var greeting = "Hiya ";
        var whozit = prompt("please enter your name");
        alert (greeting + whozit + "!");
        return; 
   }

Example - writing a function definition in a document.

A function definition is written in a script section in a document.

It is usually placed in the document head, not the body.

<head>
    <title>IT 581 Example</title>

    <script>
      <!--
        //This function is defined in the document head
        
        function greet() 
        {
            var greeting = "Hiya ";
            var whozit = prompt("please enter your name");
            alert (greeting + whozit + "!");;
            return; 
       }
      //-->
    </script>

</head>

Look at the source code of Example as a complete document.


Calling a function

A function definition by itself doesn't "do" anything.

The function will only be executed when it is used in a program statement.

This action is referred to a calling the function.

A user-defined function that returns a value is used much the same way as a standard function such as Math.round.

You provide the arguments and use the function in the expression the way you would a variable or a standard function.

A user-defined function that is a procedure - that does not return any value - is similar to document.write or alert.

You can use it as a statement by itself.

A function definition by itself doesn't "do" anything. The function has to be called.


Example : calling a function in a document.

Here we add a script section with a call to the function.


    <h1>Use a function</h1>

    <script">
      <!--
        //This script calls the function that was set up in Example above
    
        greet();

      //-->
    </script>

Both the definition and the call must be in the page.

In this example, the definition is in the head and the call in the body.

Look at the source code of Example as a complete document.


Functions as event handlers

If a function is defined in a script section of a document, it can be called from other parts of the document, including event attributes such as onclick.

Functions let you separate the JavaScript event handler from the HTML element where the event occurs. To do so


Example - using a function as an event handler.

However it is not called until the button is clicked.

<head>
    <title>IT 581 Example</title>
oz
    <script>
      <!--
        //This function is defined in the document head
        
        function greet() 
        {
            var greeting = "Hiya ";
            var whozit = prompt("please enter your name");
            alert (greeting + whozit + "!");
            return; 
       }
      //-->
    </script>

</head>

<body>
    <h1>Use a function as an event handler</h1>

    <!-- The function is called as the event handler for this button -->

    <input type="button"
           value="Click me"
           onclick="greet();"
    />

</body>

Look at Example 3 as a complete document.

The script section must appear before the calls. For this reason, function definitions are usually placed in the head part of the document.


Another Example: Hiding and revealing text

Uses techniques similar to the dropdown menus.

The script:

<script > function show(shID) { if (document.getElementById) { // check if method is supported document.getElementById(shID).style.display = 'block'; } } function hide(shID) { if (document.getElementById) { // check if method is supported document.getElementById(shID).style.display = 'none'; } } </script>

And the html:

Other Readings
(Click to show) (Click to hide>

<h3>Other Readings <br /> <span onclick="show('links');">(Click to show)</span> <span onclick="hide('links');">(Click to hide></span></h3> <div id="links"> <ul> <li>CSS Selectors <li> <li>W3C CSS Validator <li> <li> CSS Zen Garden <li> <li> Separation: The Web Designer’s Dilemma <li> </ul> </div>

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, 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   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.

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

    
    // ONLY this JavaScript is in 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  src="hello.js">
      </script>

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

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

Here is the complete example.



Using functions and external JavaScript files.

Function definitions can be written in an external file.

This lets you keep most of the JavaScript code separate from the HTML.

It is useful if you want to reuse a function - for example the swap_pic() function in the library file below.

JavaScript Function Examples: Swap pictures

Image Sources

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 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.


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 this link

The function has two arguments. The first should be the id of the image. The second should be the URL of the new source.


   <script  src="http://wyrd.hood.edu/~dong/it581/s2015/lib/library_581.js"> </script>
   

Handling onmouseover and onmouseout events

When you click on an element of a web page, such as a button or link, or type text into a box, you are initiating an event - the occurence of an action on the document that can be detected and responded to.

What happens in response is called handling the event. The browser automatically handles some events - when you click on a hyperlink, it fetches and displays the linked page.

Most elements on a web page can have events associated with them. The events most commonly used are clicking on the element, moving the mouse pointer over the element, and moving the mouse pointer away from the element.

This example shows handling mousever, mouseout and onclick events and uses swap_pic function. 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 HTML 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.

Comments to: dong@hood.edu
Last Modified: 22 July 2015. 15:37