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

Show & hide toggle needing to click 2 times to activate?

I am trying to make a show/hide toggle for a div element. The div element is by default already showing when the webpage is start up. My code keeps requiring me to press 2 time before I can hide the div for the first time, I am very confused as to the reason why...

Code sample here

const myToggle = document.getElementById('myToggle'); const areaDiv = document.getElementById('areaDiv');

myToggle.addEventListener('click', () => { toggleShow(areaDiv, myToggle); })

function toggleShow(target, button){ let toggle = target.style.display;

if(toggle == "block"){ target.style.display = "none"; button.textContent = "show" }else{ target.style.display = "block"; button.textContent = "hide" }

}

3 Answers

It's quite a while back, but if my memory is correct. The issue was due to "target.style.display" was not initially "none", but instead it is "auto" because I didn't set it up in the CSS.

so first click, it checks if (auto == block), which is false, and it turn the "target.style.display" to "block". which doesn't hide the element.

so it has to go on the second click to see that (block == block), so it turns the "target.style.display" to "none", which hides the element.

the solution is to set the "target.style.display" in the CSS file to block, so on first click it is already of that value

Oh I found out the cause, it's because the CSS style sheet did not specify the display = "block" originally.

Pragnesh Makwana
Pragnesh Makwana
6,607 Points

Hi Sunny, I'm having the same situation but i couldn't understand your answer. Can you please elaborate ? Thank You