UNIT 9 • STAGE 5 OF 7
Make the form interactive: show a thank-you message on submit
HTML builds the structure of a page. CSS controls how it looks. JavaScript controls how it behaves. With JavaScript, your page can respond to things the user does: clicks, keyboard input, form submissions.
Right now your submit button reloads the page when clicked. That is the browser's default behavior. In this stage you will write JavaScript that intercepts that click and shows a thank-you message instead.
You will use three tools for this:
document.getElementById(), finds an element on the page by its id attribute and gives you control over itaddEventListener('submit', ...), listens for the form's submit event and runs your code when it firese.preventDefault(), stops the browser's default behavior (the page reload) so your code can run insteadstyle.display, changes whether an element is visible ('block') or hidden ('none')You write JavaScript between <script> and </script> tags, placed just before the closing </body> tag. This placement means the HTML loads first, so your JavaScript can find the elements it needs to work with.
First you need to style the thank-you message that JavaScript will reveal. Add this CSS just above </style>:
Find the closing </form> tag inside your #community-form section. Add the thank-you <div> right after </form>, still inside .form-wrap:
Notice that #thank-you has display: none in the CSS. It exists on the page but is invisible. JavaScript will change this to display: block when the form is submitted.
Find the closing </body> tag at the very bottom of your code. Add this just before it:
document.getElementById('recipe-form'), searches the HTML document for the element with id="recipe-form" and stores a reference to it in the variable form. Now you have a handle on that element.document.getElementById('thank-you'), does the same for the thank-you <div>. Stored in the variable thankYou.form.addEventListener('submit', function(e) { ... }), tells the browser: whenever this form fires a submit event, run the code inside the curly braces. The e in function(e) is the event object, which gives you access to that event.e.preventDefault(), the submit event's default behavior is to send the form data and reload the page. This line cancels that so your code runs instead.form.style.display = 'none', hides the form after submission. The user no longer needs to see it.thankYou.style.display = 'block', reveals the thank-you message. The CSS had it hidden; this one line makes it appear.After adding the JavaScript, scroll down in your preview to the form section. Fill in any text and click Submit. The form should disappear and the thank-you message should appear in its place. That is your first JavaScript interaction working live.
Your page now responds to user input. In Stage 6 you will polish the page: refining spacing, adding a footer, and making the whole thing feel finished.