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 JavaScript and the DOM (Retiring) Making Changes to the DOM Styling Elements

Devjyoti Ghosh
Devjyoti Ghosh
2,422 Points

For the first time toggling requires 2 clicks to hide with my code

Here is my code http://w.trhou.se/r2dgh13tiv

The only change I have made from the teachers code is that I have reversed the if else statements. I am not sure why that leads to using 2 clicks to hide the content for the first time.

1 Answer

Steven Parker
Steven Parker
229,644 Points

The display mode is not (explicitly) "block" initially.

By testing for "none", the example code in the video works no matter what value display has to begin with. This makes the code more robust and less likely to to affected by browswer differences.

Without moving any lines, you can make your code work by changing both instances of "block" to empty strings:

toggleList.addEventListener("click", () => {
  if (list.style.display === "") {
    toggleList.textContent = "Show List";
    list.style.display = "none";
  } else {
    toggleList.textContent = "Hide List";
    list.style.display = "";
  }
});
Devjyoti Ghosh
Devjyoti Ghosh
2,422 Points

What's the difference between block and empty strings?

Steven Parker
Steven Parker
229,644 Points

If there is no CSS they will be the same. But setting "block" has inline specificity (the highest), which will override any CSS rules. The empty string just removes any inline setting, whilch will allow any existing CSS setting to apply.