Toggle visibility of the current element

I’m trying to write a function toggle_active to show the hidden content on a click, and collapse the content again on one more click. Sadly, it does not work. Could you help me modify it?

function toggle_active(this){
  var x = this.nextSibling;
  if (x.style.display === "none") {
    x.style.display = "block";
  } else {
    x.style.display = "none";
  };
}
.daccord_b{
    display:none;
}
<header class="ca_h" onclick="toggle_active(this);">
    <i class="i i-plus ca_hi"></i>
    Title
</header>
<div class="had daccord_b">Hidden content</div>

Answer

Use method nextElementSibling to return the next item. And it is not necessary to use the if {} operator.

Don’t use this for arguments in functions.

The more correct way for your task is method toggle(), which your class uses in css .daccord_b.

function toggle_active(el) {
    var x = el.nextElementSibling;
    x.classList.toggle("daccord_b");
}
.daccord_b {
    display: none;
}
<header class="ca_h" onclick="toggle_active(this);">
    <i class="i i-plus ca_hi"></i>
    Title
</header>
<div class="had daccord_b">Hidden content</div>

Second solution using style.display.

function toggle_active(el) {
    var x = el.nextElementSibling;
    x.style.display = x.style.display === 'block' ? 'none' : 'block';
}
.daccord_b {
    display: none;
}
<header class="ca_h" onclick="toggle_active(this);">
    <i class="i i-plus ca_hi"></i>
    Title
</header>
<div class="had daccord_b">Hidden content</div>

Leave a Reply

Your email address will not be published. Required fields are marked *