CJCoding With Joseph
15free / daySign inCreate account

JavaScript For Web

Edge Cases & Clean Up

Mini Post Project

At 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:

  1. Create a new <div> element and store it in a variable called newPostEl. This will be the main container for the post.

  2. Add the CSS class "post" to newPostEl so it uses the correct styles from the CSS file.

  3. Create a new <p> tag and store it in a variable called postTextEl.

  4. Set the text inside of the <p> tag to the value that was passed into the function through the text parameter.

  5. Add the <p> tag inside the <div> container using .appendChild().

  6. Finally, instead of immediately adding the new post to the page, we will return the newPostEl element. Returning it gives us more flexibility since we can decide where and when to add it later.

Members only

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.