@mbrasseau ah yes, this is an interesting one. When I originally wrote this, I deliberately used a <div>
instead of a <form>
because it meant I could avoid having to explain a couple of things that I thought would confuse people at that point.
Maybe I should have used <form>
— it is certainly better semantics.
Basically, when you have a button inside a form on a page, and you click it, the default behavior is that the form will be submitted. That means the browser tries to send the data the form contains to the server, and then sends you back to a destination page.
We haven’t specified a place on the server to send the data, or a destination page to go to after the form has submitted, so the browser basically just refreshes the current page. This is why your number flashes for a second then disappears.
You can stop the form from submitting using a method called preventDefault()
, which is called on the event object of the event that fires when the form submits — this can be a click event on the button, or a submit event on the form itself.
In our case, we already have this in the code:
guessSubmit.addEventListener('click', checkGuess);
You click the button, it checks whether the guess is correct. To make this work when you are using a <form>
, we could update it to this:
guessSubmit.addEventListener('click', function(e) {
e.preventDefault();
checkGuess();
});
So we’ve added an anonymous function inside the addEventListener
call, in which we specify an e
parameter to represent the event object. Then inside the function we call e.preventDefault()
to stop the form from submitting, and then call the checkGuess()
function.
That’s quite a lot of new concepts to introduce, which is why I think I avoided it in the first place.