Sometimes when you punch in a passcode, you might make a mistake and hit something by accident. Let's give the player a helping hand and let them clear a digit or reset their guess completely. And we'll be nice and not give them a penalty for this.
Go into your enterPasscode function. Find the section where the Try Passcode button is created. We're going to add these buttons right above that.
I'm using ×
(×
) for clear and ←
(←
) for backspace. If you'd rather use the words, go right ahead.
In the addToPasscode function, we need to display the backspace and clear buttons. We don’t need to check anything here because adding a value automatically means there is at least one number we could clear. I hope it’s ok that I’m cramming each of these into one line of code.
You may remember that we use document.getElementById()
to gain access to an element on the HTML page. In this case, we
use it to find each button we created.
When we made the buttons in the last step, we included the class
with the button
class='hide'
. Here, we are using the setAttribute method to change the
class from hide
to show
.
We do this for both of the buttons so they appear when there is at least one digit punched in for the passcode. If no digits are punched in yet, there's no reason to have a backspace or clear key, so that's why we start with them hidden.
We need a function that will handle the backspace and clear buttons. When we call the function, we send in
this.id
as an argument. That will tell our
function which button was pressed because it sends the button's id, which is either
"clear" or "backspace".
If the player clears all the digits from the passcode they're entering, then we don't need these buttons, so we can hide them again.
For this we do need to check the length of the player.guessPasscode
string and we have to do so after the number is cleared.
That's a fair bit of detail, but here we go.
In order for the buttons to appear and disappear, we need to give some style to the hide
and show
classes we're using. Right now, having them doesn't do anything.
Switch over to your CSS file with all the other styles for the game. Create these new style rules. As with adding functions, don't put them inside any other attribute's open and close braces.
You only need the show
and hide
styles, but I added some style code for the appearance of the
buttons too. I made them the same, but you could make separate listings for each if you want them too look
different.
Remember, to be able to select the #backspace
element, we have to first get inside
the #navigation
box. That's why we use #navigation
#backspace
and #navigation #clear
to style those buttons.
And that's it. You now have clear and backspace buttons.