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

Chiwei Lin
Chiwei Lin
7,545 Points

Why "Hide List" button doesn't respond at the first click but works fine at the second click?

I replaced the condition in () with <listDiv.style.display == 'block'> in if statement instead of <listDiv.style.display == 'none'> as the teacher taught in the video like the following:

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

When saved and reloaded the page, why there's no response and hide every element inside <div class="list"> after the first click on "Hide List" button? However, the second click works pretty well. Could someone tell me why? Thanks.

1 Answer

Steven Parker
Steven Parker
218,654 Points

While the default display mode for a div element is block, the style.display property is empty by default. So the first button push actually sets it to "block", but with no visible effect. After that, the button pushes alternately toggle the setting between "none" and "block".

To fix this, you can either alter your script code to handle the default condition, or you can preset the display property to block in the HTML.

is it okay it i create a variable and assign it to true? then reassign it to false?

const hideShowBtn = document.querySelector('.hide-show');
const hideForm = document.querySelector('.hide-forms');

let itsTrue = true;

hideShowBtn.addEventListener('click', () => {
    if (itsTrue) {
        hideShowBtn.textContent = 'show';
        hideForm.style.display = 'none';
        itsTrue = false
    } else {
        hideShowBtn.textContent = 'hide';
        hideForm.style.display = 'block';
        itsTrue = true;
    }
})

it works fine but i just wanted to know if there is there a shorter way of doing it? thank you

Steven Parker
Steven Parker
218,654 Points

You don't need a new variable if you test the existing element attribute:

    if (hideForm.style.display != 'none') {