Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

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