Netscape 6, Part V: DOCJSLIB 1.1: Handling Image Clicks - Doc Javascript
Netscape 6, Part V: DOCJSLIB 1.1
Handling Image Clicks
Let's write now the handleImageClick()
event handler. This is usually the heart of the application. The Connect-Three game is played by the "O"s and the "X"s, taking turns in clicking the game's boxes. Let's list the tasks we need to do in the handleImageClick()
event handler:
- Check if the click is valid. Only empty boxes can be clicked. One way to accomplish it is by checking that the GIF is
"initialbutton.gif"
. You can use DOCJSLIB library and issue thegetSrc(id)
call to get the URL of the image's GIF. Notice that theid
passed here to thegetSrc()
function is being passed to thehandleImageClick()
event handler. The line that checks if the URL is"initialbutton.gif"
is:if (getSrc(id).indexOf('initialbutton.gif') < 0) return;
- Decide if it is an "X" or an "O" by looking at the previous move. We simply keep the last player ID in the
lastPlayedBy
variable. - Load the corresponding GIF. If the previous player was an "X," the current one is an "O," and we switch the URL to
"obutton.gif"
. The opposite occurs when the previous player was an "O". You can use DOCJSLIB'ssetSrc()
function to set the URL of the image's GIF. Its first parameter is the box'sid
, passed from the caller. Its second parameter is the new URL to load:if (lastPlayedBy == "o") setSrc(id, "xbutton.gif");
- Update the previous move. We just assign the player name to
lastPlayedBy
variable:lastPlayedBy = "x";
- Mark the clicked box with the player identity. We use a 3 by 3
grid
array that stores the player type in each box ("X", "O", or ""):
Notice that the indices of the array element above (grid[param1][param2] = lastPlayedBy;
param1
andparam2
) are passed to themakeImage()
function first and only then to the event handler. We initialize thegrid
with empty strings in the beginning of the game. - Check if there is a winner or is it a tie, and inform the user. We wrote a function that checks for a winner (Connect-Three) and another one that checks for ties.
Next: How to write the Tic-Tac-Toe's functions
Produced by Yehuda Shiran and Tomer Shiran
All Rights Reserved. Legal Notices.
Created: January 29, 2001
Revised: January 29, 2001
URL: https://www.webreference.com/js/column76/8.html