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

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
229,645 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
229,645 Points

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

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