user2937995
user2937995

Reputation:

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.getElementById('icon').onclick = function(){
    var el = document.getElementById('div');
    if ( el.style.display != 'none' ){
        el.style.display = 'none';
    }
    else {
        el.style.display = 'block';
    };
};

Upvotes: 0

Views: 2398

Answers (3)

EternalHour
EternalHour

Reputation: 8621

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

Upvotes: 0

gaurav5430
gaurav5430

Reputation: 13892

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/

Upvotes: 4

Alexis Wilke
Alexis Wilke

Reputation: 20730

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/

Upvotes: 2

Related Questions