JavaScript examples.

During this lecture we'll consider several small examples that add some interactivity to web pages using JavScript code. These examples we'll be short, relatively simple, and not very useful, but they help you better understand what you can do with elements on your page. The first example will illustrate how you can change values of input strings and the other two example will give you some ideas about creating menus and pop-up hints.

Input text and buttons.

In the first example we'll illustrate how to add a little bit functionality to the calculator, interface for which you designed in second project. This example includes an input text string and several buttons. Originally none of these buttons has any functionality. Our goal is to make them work. We will do the following things:
  1. Change the style of the input string. This string will be bigger and will have a different color.
  2. Three of our five buttons are usual character buttons; that is, they have characters A, B, and C on them. When user clicks on one of these buttons, then the corresponding character is added to the input string.
  3. One of the other two buttons should duplicate the value of the input string. For example, if the text in the input string is currently BAC, then after clicking on this button it should become BACBAC.
  4. The last button will behave like usual Reset button. In our case it will remove any value from the input string making it empty.

To achieve the first goal all we need to do is to create a corresponding style and apply it to the input element. This style can look like this:

.big_string {
  color: darkblue;
  font-size: 200%;
}
and we can apply this style using tag input with the correct value of the parameter class:
<input type=text class=big_string>

For defining new behavior of the buttons we need to define a handler of the event Click which occurs when user clicks on a button. For the first three buttons this event handler should do exactly the same thing add a particular character to the input string. Thus, we can create a new function named add_character(), which takes the character to add as an argument and adds it to the string. The defining the event handler and making it use this function can be done the following way:

<input type=button value='A' onClick="add_character('A');">
<input type=button value='B' onClick="add_character('B');">
...
Now we need to declare the function add_character() and make it work exactly the way we want it. To do that we first need to get an access to the input string element. As we know from a previous lecture we can access any element of a form by its name and we can access any form of our document by also by name. Thus, we need to name the form and the input element:
Code Result
<form name=calc_form>
 <input type=text class=big_string name=display_string value="0">
</form>
In this example we used initial value 0 for a special reason. If you click on the input string on the right from the code you'll see a window with all properties of the element input defined this way. Please notice the property value. This property contains the string entered by the user (in our case it contains 0). This means that we can control the text entered in the input string by accessing the value property of the element. We can do it like this:
document.forms["calc_form"].elements["display_string"].value
or shorter:
document.calc_form.display_string.value
Please notice that this property can be on both sides of an assignment operator. If it is on the right side, then we are reading the value, if it's of the left side, then we are assigning a new value. For example, to clear the string we can do this:
document.forms["calc_form"].elements["display_string"].value = "";
to add character 'A' to the string we can use this:
document.calc_form.display_string.value += 'A';
Now we are ready to write our add_character() function:
<script>
function add_character( ch )
{
  document.calc_form.display_string.value += ch;
}
</script>

Handler for the duplicate button is practically the same, except we need first to read the value of the input string and then assign the new value, which contains the read value two times. It can be done by:

var cur_value = document.calc_form.display_string.value;
document.calc_form.display_string.value = cur_value + cur_value;
or shorter
document.calc_form.display_string.value += document.calc_form.display_string.value;

We practically discussed how to clear out the input string. All we need to do is to define a handler that will assign the value property of the input element the empty string. In the complete example we have all these small pieces of code assembled together. We also created two different styles for our buttons. Hope you'll figure it out by yourself.

Menu.

In this example we'll try to create a simple menu. We want the following thing from our menu:
  1. It should have several items ordered in a column (one below the other).
  2. Original all item have the same color and the same background.
  3. When mouse cursor is over one of the items this item should be highlighted (we need to change color and background of the item).
  4. Upon clicking on an item we need to load a page corresponding to this item.
It's relatively easy to satisfy the first two requirements. We can use a table to order items and we can specify any background color and text color we want:
Code Result
<style>
 .menustyle {
    background-color: #b1caf3; 
    cursor: default;
    font-weight: bold;
 }
</style>
...
<table cellpadding=2 cellspacing=0 border=1 class=menustyle>
 <tr> <td> Yahoo </td> </tr>
 <tr> <td> Google</td> </tr>
 <tr> <td> Altavista  </td> </tr>
 <tr> <td> Lycos </td> </tr>
</table>
  
 Yahoo
 Google
 Altavista 
 Lycos

To change colors upon mouse movement we need to define event handlers for two events:

  • MouseOver -- to select an item (change colors)
  • and MouseOut -- to unselect the item (restore colors).
    Now let's discuss how we are going to change colors. In this example we wold like to use sub-object style of the menu item. To access this sub-object we first need to access the object itself. In this case cells of the table can be our objects; that is, <td> elements. How to access them? We already saw earlier that we can access any element on a page by giving it a specific ID and using all property of the document object (document.all['element_id']). We can use this method in this case too. However, we would like to demonstrate another way of doing it. This way uses a keyword this. this always refers to the current object. For example, if we use this keyword in an img tag, then it refers to the image element of the page:
    <img src='somefile.jpg' obClick='this.src="anotherfile.jpg"'>
    
    Thus, being used in <td> tag object this will refer to this particular cell.

    Any displayable element on a page has sub-object style that contains information about style of the element. Addressing properties of the object style we can change the look of any element. We will use only two of these properties:

  • backgroundColor, which is equivalent to style property background-color
  • and color, which is equivalent to style property color.
    That is, being used inside a <td> tag the following code will change color of the text in this particular cell:
    this.style.color = "blue";
    
    Here is a more complete example to illustrate how to combine these things together:
    Code Result
    <table border=1>
     <tr>
      <td onMouseOver="this.style.color='red'">Cell one</td> 
      <td onMouseOver="this.style.backgroundColor='yellow'">Cell two</td>
     </tr>
    </table>  
      
    Cell one Cell two
    Remember that JavaScript is case sensitive. style.color and style.Color will not work the same way.

    To fulfill the last part of the objectives we need to jump to another page (just like a link allows us to do). We could've done that by using <a> tag inside the cells, but we'll use another way. We are going to use sub-object location of the object window. location object has only three properties:

  • href,
  • pathname
  • and protocol.
    We are interested in the property href, which contains the URL of the current document. We can assign another value to this property and this makes the browser to bring us the page that new value point at. For example, to move to Yahoo page we can write this:
    window.location.href = "http://www.yahoo.com";
    
    Finally, to jump to a new page only when a user clicks we need to define handlers for the event Click for all cells in our menu:
    <td ... onClick="window.location.href = 'http://www.yahoo.com';">
    

    This file contains the complete example.

    Pop-up elements.

    The final example illustrates how to deal with pop-up objects such as menus, hints, or something like them. Our goal here is to obtain some sort of message when a user moves a cursor over a particular object, for example a word, or a table cell. This object must disappear when mouse cursor is out of it and out of the object this hint is for.

    To create such an object we'll use tag <div> defined like this:

    <div id=popup>
    </div>
    
    with the following style defined for it:
      #popup {
        visibility: hidden;
        position: absolute;
        ...
        width: 150px;
        height: 200px;
      }
    
    The most important lines of the style are emphasized with the bold font. The first of them hides this object on the page, so initially it's not visible. And the other makes its coordinate to absolute coordinates on the page. To make this object appear we will use property visibility of the sub-object style of this object, which, by the way, can be accessed by its ID as document.all['popup']. visibility property can be set to hidden to hide an object or to vivible to show it up. Thus, to make this object appear we use:
    document.all['popup'].style.visibility = "visible";
    
    and to make it disappear again:
    document.all['popup'].style.visibility = "hidden";
    

    To make our hint appear in the right place we can use two more properties of the style object:

    For example, to move top-left angle of the hint to the point (100, 50) of the browser window we need to run the following code:
    document.all['popup'].style.posLeft = 100;
    document.all['popup'].style.posTop = 50;
    

    Combining all of these together, to make our hint appear upon mouse movement over a particular object we need to define onMouseOver handler of this object like this:

    <script>
    fucntion show_hint(x, y)
    {
      document.all['popup'].style.posLeft = x;
      document.all['popup'].style.posTop = y;
      document.all['popup'].style.visibility = "visible";
    }
    </script>
    ...
    ...<td onClick="show_hint(115, 45);">I want a hint here</td>...
    

    As you may notice this object does not contain any text in it. We'll take care of it in JavaScript code. To insert some text inside this pop-up object on-fly we can use property innerHTML, which contains all HTML text inside the object. For example, for the following object:

    <div id=hint>
    This is an object with <b>ID</b>=<i>hint</i>. 
    </div>
    
    this property ( which is accessible as document.all['hint'].innerHTML) is equal to
    "This is an object with <b>ID</b>=<i>hint</i>." 
    
    Using innerHTML property we can not only get to know what's inside the object under consideration, but also assign new content to it. For example, the following line clear out the content of the object hint from the previous example:
    document.all['hint'].innerHTML = "";
    
    We can a little bit modify function show_hint() and make it take the third argument, text it should put inside the hint.

    The very last problem we need to discuss here is how to make the hint disappear. Since the condition of disappearance is "when user moves the mouse out of the hint", then it seems to be very logical to define onMouseOut handler for the hint object:

    <div id=popup onMouseOut="this.style.visibility='hidden';">
    </div>
    

    The following file contains the complete example. All coordinates in the example were chosen manually from experiments. Yes, there is a nicer way to locate the right position, but we decided not to put too many details in one example.

    Please notice, that combining examples two and three together one can do rather difficult menus.

    On the eBorCom Web Development Resources site you can find more details about JavaScript event handlers