For demonstration purposes, I refer to a JS web application I recently developed. If you’re curious, you can find the full repo here.
We’ve all had movie nights where the following scenarios take place: either you spend too much time picking a movie and you end up staying up super late to finish it or, after intensely googling reviews, you decide on a critically-acclaimed movie but it really misses the mark. Critics loved it, but you found it unpalatable.
Visitors can post likes and comments that are associated with each movie. The movies are displayed as rows of cards that contain tons of information about the movie, including a hidden comments field for users to see other comments and submit their own.
Here’s a gist of my index.html file so you can see all of the script tags in the
<head> of the file, which are pretty important for rendering each component.
We’re setting the value of addComment to “false”. This value will be toggled between “false” and “true” to hide and unhide the comments.
In the file that you’ve built out the button or text where you want the toggling feature to take place, add your event listener. For me, it’s in my movie.js file where I declared my Movie class. I’ve styled each of my movies into Semantic UI cards with a comment icon on the left-hand side so I’ll be adding my event listener there.
Grab that HTML tag and add on the event listener for a “click” event.
To explain this code in more detail…
On line 2, you’re toggling the boolean value of addComment. If it was
false, it’s now
On lines 3 to 9, these two conditional statements are either hiding or unhiding the comments and comment form depending on the boolean value of
If you’re coding along right now, you may have noticed that when the page initially renders, the comments and form (or whatever you’re hiding in your code) is not hidden! This last step fixes that.
In your CSS file, add in the following code:
I used an ID selector
# to grab my two HTML elements for comments and comments form, but you are welcome to use class names, denoted by a period
., or any other HTML selector.