Change icone and display None/block

Asked

Viewed 575 times

0

Hi, I’m trying to make sure that when the button is clicked, change the visibility of a div and the icon changes. If I remove the part that refers to the icons, the visibility is changed normally, but with the whole code, nothing happens.
function:

function changeVisibility() {
        var display = document.getElementById("showup").style.display;

        if (document.getElementById("icon").classList.contains('fa fa-angle-down')){
            document.getElementById("icon").classList.toggle('fa fa-angle-up')
        }else if (document.getElementById("icon").classList.contains('fa fa-angle-up')){
            document.getElementById("icon").classList.toggle('fa fa-angle-down')
        }

        if(display == "none"){
            document.getElementById("showup").style.display = 'block';
        }else{
            document.getElementById("showup").style.display = 'none';
        }
    }

button:

<button onclick = "changeVisibility()" class = "btn btn-success btn-md">
            <span id = "icon" class = "fa fa-angle-down"></span>
        </button>

div that has altered visibility:

<div id = "showup" class = "form-row" style = "display: none">
            Code
    </div>

Thank you in advance!

1 answer

0


I’ve identified some issues in your code:

  1. The classList.contains checks only one class at a time, and you were passing two (fa and fa-angle-down or fa-angle-up).
  2. The toggle logic wasn’t correct.

Below your code with corrected logic and some improvements like playing the elements in a variable to get more optimized and easy to understand:

function changeVisibility() {
  var $showup = document.getElementById("showup");
  var $icon = document.getElementById("icon");
  
  if ($icon.classList.contains('fa-angle-down')) {
    $icon.classList.add('fa-angle-up');
    $icon.classList.remove('fa-angle-down');
  } else if ($icon.classList.contains('fa-angle-up')) {
    $icon.classList.add('fa-angle-down');
    $icon.classList.remove('fa-angle-up');
  }

  if ($showup.style.display == "none") {
    $showup.style.display = 'block';
  } else {
    $showup.style.display = 'none';
  }
}
<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet"/>
<button onclick="changeVisibility()" class="btn btn-success btn-md">
  <span id="icon" class="fa fa-angle-down"></span>
</button>

<div id="showup" class="form-row" style="display: none">
  Code
</div>

  • I get it, I’ll test it when I get home. Thank you very much!

  • It worked, thank you very much man :)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.