user198989
user198989

Reputation: 4665

It closes DIV on second click, why?

I have a javascript function which should close the div on click. However, it works on the second click. How can I avoid that ?

JavaScript

function showhide(id) {
    var e = document.getElementById(id);
    if(e.style.display == 'block') {
        e.style.display = 'none';
    } else {
        e.style.display = 'block';
    }
}

HTML

<div id="foota123">
    Content
    <div onclick="showhide('foota123')" class="iks">X</div>
</div>

Upvotes: 0

Views: 248

Answers (5)

user488187
user488187

Reputation:

e.style refers to the style attribute of the div (style="..."). First time through, there is no style attribute on the div. The condition is false and the code sets a style attribute of:

<div style="display: block">

The second time through, the if condition is true, and the style of the block is set to "none". So it disappears.

Upvotes: 4

Akilsree1
Akilsree1

Reputation: 462

It works for me. Html code

  <div id="foota123">
      Content
  </div>
  <div onclick="showhide('foota123')" class="iks">X</div>

Script

<script type="text/javascript">
   function showhide(id) {
var e = document.getElementById(id);

if(e.style.display == 'block'){
  e.style.display = 'none';
}
else{
   e.style.display = 'block';
   }
}
 </script>

OR style="block" is also a better option.

Upvotes: 1

Ja͢ck
Ja͢ck

Reputation: 173542

The style property is empty by default; for example:

var e = document.createElement('div');
e.style.display; // ""

Simply reversing the condition should fix that:

function showhide(id) {
    var e = document.getElementById(id);
    e.style.display = e.style.display == 'none' ? 'block' : 'none';
}

Upvotes: 2

user2575725
user2575725

Reputation:

Your code does not handles the computed style on the element, hence on first click the element is still in display:block.

Try this with jQuery:

function showhide(id) {
   $('#'+id).toggle();
}

$.toggle() will show the element if it is hidden else hide.

Upvotes: 3

Wesley Smith
Wesley Smith

Reputation: 19571

Try this, if you want straight javascript, the jQuery answer is better though :)

function showhide(id) {
   var e = document.getElementById(id);
   if(  e.style.display!=='none' )  e.style.display = 'none';
   else e.style.display = 'block';
}
<div id="foota123">
Content
<div onclick="showhide('foota123')" class="iks">click me</div>
</div>

Upvotes: 1

Related Questions