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';
    }
};

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.

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

Glad you solved your issue.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.