SEARCH
0-9 A B C D E F G H I J K L M N O P Q R S T U V W X Y Z
Prev | Current Page 94 | Next

Jonathan Snook, Aaron Gustafson, Stuart Langridge, and Dan Webb

"Accelerated DOM Scripting with Ajax, APIs, and Libraries"

className = '';
selectedPiece.className = '';
}
selectedPiece = null; // reset selected
}
window.onload=function()
{
var el = document.getElementById('pieces');
el.onclick = checkPiece;
}

CHAPTER 2 n HTML, CSS, AND JAVASCRIPT 52



  • Shark

  • Lion

  • Lion

  • Shark

  • Dolphin

  • Squirrel

  • Dolphin

  • Squirrel




In this very simple example shown in Figure 2-6, each piece is represented by a list item
within an unordered list. I attached the event handler to the unordered list container (the UL).
Figure 2-6.Match game
window.onload=function()
{
var el = document.getElementById('pieces');
el.onclick = checkPiece;
}
CHAPTER 2 n HTML, CSS, AND JAVASCRIPT 53
Any time something within the unordered list is clicked, the event is sent to the
checkPiece function.
function checkPiece(evt)
{
evt = evt || window.event;
var target = evt.target || evt.srcElement;
currentPiece = target;
...
}
The event target is located and assigned to a variable called currentPiece. If no piece has
been selected, the current piece is assigned to a placeholder called selectedPiece. If there is a
selected piece, the innerHTML is compared with that of the current piece. If they match, the
user is notified and the selected piece placeholder is cleared. If they don??™t match, the pieces
are reset and the user tries again.


Pages:
82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106