Skip to content Skip to sidebar Skip to footer

Toggle Display Only Working On Second Click

I have a div that is display:none which should appear when an icon is clicked. My function works but always on the second click. Any ideas what's wrong with the function? document.

Solution 1:

Change your test to the "positive"

if ( el.style.display == 'block' ){

And it will work.

The default is probably not exactly 'none'.

Using jQuery would make that a lot easier, see http://api.jquery.com/toggle/


Solution 2:

el.style would refer to inline style , not global style.

so change your code to

<div id="nav_form_container" style="display:none">

and the code will work.

http://jsfiddle.net/2hobbk7u/2/


Solution 3:

This is working for me. I believe what you may have been doing was using the div as a selector instead of an ID on your variable.

FIDDLE

HTML:

<button id="icon">Test Button</button>
<div id="test" style="display: none;">I am hidden</div>

JS:

document.getElementById('icon').onclick = function(){
    var el = document.getElementById('test');
    if ( el.style.display != 'none' ){
        el.style.display = 'none';
    }
    else {
        el.style.display = 'block';
    };
};

Post a Comment for "Toggle Display Only Working On Second Click"