JavaScript For Web
Edge Cases & Clean Up
Mini Post ProjectAt this point we have a working project, but there is a minor issue. If the user presses Post without any text, the JS will build an empty post box. We want to block this so it does not do anything when there is no text inside of the input element.
Refactoring the Code into a Separate Function
Right now, all of our post creation code is written directly inside the button’s click event. This works, but it makes the code harder to read and expand later. To make it cleaner, we will move the logic that builds the post into its own function.
We’ll create a new function called buildPostElement that takes one parameter called text. This text will come from the input field in our HTML. Inside this function, we will use the DOM methods to create the elements that make up a single post.
Here’s what the function will do step by step:
Create a new
<div>element and store it in a variable callednewPostEl. This will be the main container for the post.Add the CSS class
"post"tonewPostElso it uses the correct styles from the CSS file.Create a new
<p>tag and store it in a variable calledpostTextEl.Set the text inside of the
<p>tag to the value that was passed into the function through thetextparameter.Add the
<p>tag inside the<div>container using.appendChild().Finally, instead of immediately adding the new post to the page, we will return the
newPostElelement. Returning it gives us more flexibility since we can decide where and when to add it later.
Keep reading this lesson
You've reached the end of the free preview. Unlock the rest of this lesson plus 10 more lessons in JavaScript For Web.
- Unlimited coding questions
- Unlimited access to all classroom material
- Weekly live call for questions and guidance
- 3,000 AI tutor tokens / month
- Personal SQL database (3 MB)
- Progress tracking
Cancel any time.