Introducing DOCJSLIB, Part I: Writing the Event Handler - Doc JavaScript
Writing the Event Handler
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.
Created: October 12, 1998
Revised: October 12, 1998
URL: https://www.webreference.com/js/column27/appevent.html