Reading: Review the First Splash page on the Mozilla Developers Network.
Work though the steps in the First Splash page to build the number guessing game application. You do not need to make any changes to the application (yet), but you should review the supporting material on the page so you understand how it works.
Make the following changes to the guessing game application:
Currently, the application looks up the UI elements using the class name associated with
the element. This is reasonable when you want to manipulate every element with the same class
uniformly. However, in most cases, the script manipulates each UI element uniquely. Therefore,
it would make more sense to look them up using an id
attribute.
Add an id
attribute to the appropriate elements (and remove the
class
attribute if it is otherwise unused). Change the uses of querySelector
to getElementById
Modify the application so that it sets the background color of the list of guesses tried so far to different shades of red starting at 'rgb(255, 255, 255)' (representing white) and subtracting, e.g., 10 from the green and blue values after each guess.
For example, the background color should step through 'rgb(255, 255, 255)', 'rgb(255, 245, 245)', 'rgb(255, 235, 235)', etc., as more guesses are made. The effect this has is that the background of the list of previous guesses becomes a progressively more intense shade of red as more and more guesses are made, warning the user that they are approaching the maximum number of guesses available.
Remember to reset the background color when the game is reset.
Hint: The rgb()
is not a JavaScript function. However, you can use it in your
JavaScript as a string to set the style.backgroundColor
property of an element.
To inject the value of a JavaScript variable into that string, use the template literal
syntax. For example, `rgb(255, ${greenValue}, ${blueValue})`
will access
the values of the JavaScript variables greenValue
and blueValue
,
convert them to strings, and insert them into the overall string. This functionality is
enabled by the backticks surrounding the literal.
Currently, it is necessary to manually click on the "Submit guess" button to submit each guess. Let's change that, so typing the 'Enter' key after typing the number will also submit the form.
To do this, we need to add an event handler to the guessField that handles 'keypress' events. One such event is generated whenever a key is pressed while that input control is in focus. The event handling function should be something like:
function submitGuess(event) { // Check if the pressed key is 'Enter' if (event.key === 'Enter') { guessSubmit.click(); // Simulate a click on the submit button } }
For this lab, submit a single HTML file containing your modified version of the guessing game application to Canvas.
Last Revised: 2024-09-20
© Copyright 2024 by Peter Chapin <peter.chapin@vermontstate.edu>