HTML and CSS Reference
In-Depth Information
Tip: JavaScript and many other languages also provide a string method called substr that works a
little differently. The second argument of substr is the length of the piece of string. For the class
name example,
class.substr(0,3) , coincidentally, also produces "MAT"
class.substr(3,4) produces "1420"
class.substr(3,1) produces "1"
In our implementation of the quiz, we use the portion of the string starting from the position numbered 1,
that is, the second position, to the end of the string.
Once we create these new HTML elements, we use addEventListener to set up events and event
handlers. The addEventListener method is used for a variety of events. Remember, we used it on the
canvas element in Chapter 4.
For the quiz application, the following statement sets up the JavaScript engine to “listen” for clicks for
each element and to invoke the pickelement function that well create.
thingelem.addEventListener('click',pickelement,false);
(The false in this statement refers to a technicality involving other possible listeners for this event.)
In the pickelement function, youll see code containing the term this , such as
thisx= this.style.left;
In the code, this refers to the current instance, namely the element that the player clicked. We set up
listening for the event for each element so when pickelement is executed, the code can refer to the
specific element that heard the click using the this . When the player clicks on the Brazil block, the code
knows it, where by “knows” I am anthropomorphizing the program more than I would like. Putting it another
way, the same pickelement function will be invoked for all the blocks we have placed on the screen, but,
by using this , the code can refer to the specific one that the player clicks on each time.
Note: If we didn't have these elements and the capability to do the addEventListener and refer to
the attributes using the this (forgive the awkward English) and instead drew stuff on a canvas, we
would need to perform calculations and comparisons to determine where the mouse cursor was and
then look up the corresponding information in some way to check for matches. (Recall the coding for
the Slingshot in Chapter 4.) Instead, the JavaScript engine is doing much of the work, and doing it
more efficiently—faster—than we could by writing the code ourselves.
After the new HTML is created, its contents are set using the innerHTML attribute. Next, the new element
is added to the document by being appended as a child of the body element. This may seem odd, but it is
how things are done.
d.innerHTML = (
"<div class='thing' id='"+uniqueid+"'>placeholder</div>");
document.body.appendChild(d);
 
Search WWH ::




Custom Search