Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript

Styling Elements

It works fine but I'm having trouble understanding the logic.

toggleList.addEventListener('click', () => {
  if(listDiv.style.display == 'none'){
  toggleList.textContent = 'Hide list';
  listDiv.style.display = 'block';
}
  else {
  toggleList.textContent = 'Show list';
  listDiv.style.display = 'none';
}
});

The if statement condition is listDiv.style.display == 'none' which means that the listDiv element is not visible. So why the text on the button should say 'Hide list' (as this line applies toggleList.textContent = 'Hide list' ; ). Shouldn't the button say 'Show list' when listDiv is not visible?

fixed code formatting

4 Answers

Hi Katre,

Let's imagine that at the moment, the list is hidden. That means the button should read "Show list". Clicking the button should show the list.

Now you click the button and the click handler is executed.

Since the list is currently hidden, its display property will be none and the if condition will be true. The 2 statements in the if block are going to be executed.

Since we're about to show the list, we would want the button text to be updated to "Hide list". We're going to be showing the list so the button needs to indicate that it will hide the list if you click it. Then the display property is set to block to show the list.

At this point, the list is showing and the button reads "Hide list"

Ben Schroeder
Ben Schroeder
22,818 Points

Remember that the event is fired when the button is clicked. If the button is clicked and the element is hidden, that means that the button you just clicked was labelled "Show button," and now must display "Hide button" (presumably after showing it).

Does that make sense?

Unfortunately not.

Finally I get it. How didn't I see it before :D My flaw was that I didn't think of the condition as a condition, but as a statement that is also being executed after the click.