Change icon and display none / block

0

Hello, I'm trying to make so 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. Home functions:

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 changed visibility:

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

Thank you in advance!

    
asked by anonymous 31.08.2017 / 22:03

1 answer

0

I have identified some problems in your code:

  • The'classList.contains' checks only one class at a time, and you were passing two ( fa and fa-angle-down or fa-angle-up ).
  • The toggle logic was not correct.
  • Below is your code with corrected logic and some improvements like playing the elements in a variable to stay 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>
        
    31.08.2017 / 22:14