Java Reference
In-Depth Information
Note: Naming Conventions
You may have noticed that all of these variables have been prefixed with the
$
symbol, which is a common convention used when naming variables that
refer to DOM elements.
Our next job is to create a function called
update()
that can be used to update an element
on the page. Add the following function to the top of the scripts.js file:
scripts.js
(excerpt)
/// view functions ///
function update(element,content,klass) {
var p = element.firstChild ||
document.createElement("p");
p.textContent = content;
element.appendChild(p);
if(klass) {
p.className = klass;
}
}
This function has three parameters. The first parameterr is the element that is to be updated.
The second parameter is for the content that it is to be updated with. A class can also be ad-
ded to the content that is added using the third parameter, which is called
klass
because
class
is a reserved word in JavaScript.
The first line of the function checks to see if the element already has a first child and assigns
it to the variable
p
. If it doesn't, then it creates a new paragraph element. The
textCon-
tent
property is then set to the content provided as an argument and it is added to the
element using the
appendChild()
method.
Now we need to update some of our existingfunctions to use this new function to update
the HTML instead of using dialogs. The first thing we need to do is udpate the score ele-
ment with the score once the game starts. Add the following line of code to the start of the
play()
function, right after the
score
variable has been initialized:
scripts.js
(excerpt)
