0

Hi all,

I have a hidden division that is supposed to appear when the button, as shown below, is clicked by the user. The division is hidden on page load, and does actually appear when the button is clicked, but nothing happens on the first click. To clarify, you have to click the button twice for the div to appear the first time - and then only once after that to make it disappear and reappear again and again. Why does it need that second click to work the first time? How does someone fix this?

I've done some research but all I seem to be reading is to 'reverse the if statement'. I didn't believe it, but tried it - obviously with no success.

Thanks in advance for any help.

HTML

<button type="button" class="btn green" id="createNew">Create</button>

<div class="newForm hide" id="newForm">
    <!-- Hidden division content  -->
</div>

Javascript

var button = document.getElementById('createNew');
button.onclick = function() {
    var div = document.getElementById('newForm');
    if (div.style.display !== 'none') {
        div.style.display = 'none';
    }
    else {
        div.style.display = 'block';
    }
};

Edited by mmcdonald

2
Contributors
3
Replies
17
Views
3 Years
Discussion Span
Last Post by JorgeM
0

Based on your description it would seem to me that the first time you click, the if condition is True and the second time its False, hence the need to click twice. Would need to see the rest of the code and use my browser console for testing to know for sure.

0

I don't know why I couldn't visually see what you've just said! Thanks Jorge you've done it again! I've rebuilt my code to the following, and it works a treat:

var button = document.getElementById('createNew');
var div = document.getElementById('newForm');

    div.style.display = 'none';

    button.onclick = function() {
        if (div.style.display !== 'none'){
            div.style.display = 'none';
        }else {
            div.style.display = 'block';
        }
    };

The difference is simple, I've set div.style.display = 'none'; on page load, rather than just in the true section of the if statement.

Thanks again,
Michael

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.