The onClick Event Processing

This event occurs when a user clicks on the form element. The onClick event handler is typically used with buttons.

Switching the lamp with two buttons

In this example the lamp color is controlled by two buttons.

Upon clicking a button the function LampOn() or LampOff() will be called. These functions modify the src property of the image object and force the browser to substitute the displayed lamp image with another one:

function LampOn()
{
   document.images[0].src="ballred.gif";
}

function LampOff()
{
   document.images[0].src="ballblue.gif";
}

Switching the lamp with one button

In this example a similar functionality is achieved with only one button.

    ... or with a link

We use a variable LampState to encode the lamp color. The value 1 of this variable corresponds to the blue color and the value 1 to the red one. Initially, this value is 0 corresponding to the initial lamp color blue. Clicking a button (or the link) will cause calling the function LampOnOff(). This function checks the value of LampState and modifies the image property src as above. Additionally, the value of LampState is set to 1 - LampState. That is, if before clicking the button LampState was 1, it becomes 0 after that. Similarly, if it was 0, it becomes 1.

var LampState = 0;
function LampOnOff()
{
   if (LampState == 0)
      {
         document.images[1].src="ballred.gif";
         LampState = 1 - LampState;
      }
      else 
      {
         document.images[1].src="ballblue.gif";
         LampState = 1 - LampState;
      }
}

Switching two lamps on a mouse click

   

Here we modify the src property of two image objects within one function. The variable lamp is used to refer to the the lamp image number in the array images maintained by the browser. Since the image numbers start with 0, the ones for our lamps are 2 and 3. The instruction lamp = 5 - lamp is used to alternate the lamp indices between 2 and 3. Try to figure out how it works by tracking the value of this variable.

var lamp = 2;
function LampSwitch()
{
   document.images[lamp].src="ballblue.gif";
   lamp = 5 - lamp;
   document.images[lamp].src="ballred.gif"; 
}

An alternative way for achieving the same effect is to swap the value of the src property of images number 2 and 3:

   

This is implemented in the following function. In this case we do not need the valiable lamp. Note that the lamp image indices of the involved lamps are now 4 and 5.

function LampSwitch2()
{
   var temp = document.images[4].src;
   document.images[4].src = document.images[1].src;
   document.images[5].src = temp; 
}