The Essential Guide to HTML5

(Greg DeLong) #1

QUIZ


Note that the position is never changed, but the z-index only works if position has been specified in a
style.

When the code calculates that it is time for the video clip, it changes the visibility and the z-index and then
invokes the play method.

v = document.getElementById("vid");
v.style.visibility = "visible";
v.style.zIndex = "10000";
v.play();

Tip: CSS has its own language, sometimes involving hyphens in terms. The CSS term for expressing
how elements are layered on the screen is z-index; the JavaScript term is zIndex.

With this considerable JavaScript, HTML, and CSS knowledge, we are now ready to describe the details of
the quiz application.

Building the application and making it your own


The knowledge base for the quiz is represented in the facts variable, which is an array of arrays. If you
want to change the quiz to another topic, one that consists of pairs of names or other text, you just need
to change facts. Of course, you also need to change the text that appears as an h1 element in the body
element to let the player know the category of questions. I defined a variable named nq, for number in
each quiz (the number of pairs to appear onscreen) to be 4. You can, of course, change this value if you
want to present a different number of pairs to the player. The other variables are used for the original
positions of the blocks and to hold status information, such as whether its a first click or a second click.

I created three functions for this application: init, setupgame and pickelement. I could have combined
init and setupgame, but made them separate to facilitate a replay button. Table 6-3 describes these
functions and what they call or are called by.

Table 6-3. Functions in the Quiz Application

Function Invoked By / Called By Calls

init Invoked by the action of the onLoad in the <body> tag setupgame

setupgame called by init

pickelement Called as a result of the addEventListener calls in setupgame

The setupgame function is where the HTML is created for the blocks. Briefly, an expression using
Math.random is evaluated to pick one of the rows in the facts array. If that row has been used, the code
tries again. When an unused row is found, it is marked as used (the third element, index value 2) and the
blocks are created.
Free download pdf