javascripthtmlcssfont-awesome

How to make font-awesome caret change from caret-right to caret-down?


The simple code below works if I use fa-folder in the i tag and fa-folder-open in the javascript, but if I substitute fa-caret-right and fa-caret-down, it does not work, and I cannot see why. Any help would be greatly appreciated. Thanks!

<html>
<head>
<style>
    .accordion {
    cursor: pointer;
    }
    .panel {
    display: none;
    }
    .panel.show {
    display: block;
    margin-left: 20px;
    }
</style>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.6.3/css/font-awesome.min.css">
</head>
<body>
    <p class="accordion"><i class="fa fa-folder" aria-hidden="true"></i>&nbsp;&nbsp;Building Guides</p>
    <div class="panel">
    <p><i class="fa fa-file-pdf-o" aria-hidden="true"></i>&nbsp;&nbsp;Accessory Structures Building Guide 2012</p>
    <p><i class="fa fa-file-pdf-o" aria-hidden="true"></i>&nbsp;&nbsp;Basement Finish Building Guide 2012</p>
    <p><i class="fa fa-file-pdf-o" aria-hidden="true"></i>&nbsp;&nbsp;Decks Building Guide 2012</p>
    </div>
<script>
var acc = document.getElementsByClassName("accordion");
var i;

for (i = 0; i < acc.length; i++) {
acc[i].onclick = function(){
    this.nextElementSibling.classList.toggle("show");
    this.firstChild.classList.toggle("fa-folder-open");
    }
}
</script>
</body>
</html>

Solution

  • You need to turn the right class OFF when you turn the down class ON. Also, I got rid of the non-breaking spaces, and used CSS to render the same result -- cosmetic but way less annoying.

    var acc = document.getElementsByClassName("accordion");
    var i;
    
    for (i = 0; i < acc.length; i++) {
      acc[i].onclick = function() {
        this.nextElementSibling.classList.toggle("show");
        this.firstChild.classList.toggle("fa-caret-right")
        this.firstChild.classList.toggle("fa-caret-down");
      }
    }
    .fa {
      width: 20px;
    }
    
    .accordion {
      cursor: pointer;
    }
    .panel {
      display: none;
    }
    .panel.show {
      display: block;
      margin-left: 20px;
    }
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.6.3/css/font-awesome.min.css" rel="stylesheet" />
    <p class="accordion"><i class="fa fa-caret-right" aria-hidden="true"></i>Building Guides</p>
    <div class="panel">
      <p><i class="fa fa-file-pdf-o" aria-hidden="true"></i>Accessory Structures Building Guide 2012</p>
      <p><i class="fa fa-file-pdf-o" aria-hidden="true"></i>Basement Finish Building Guide 2012</p>
      <p><i class="fa fa-file-pdf-o" aria-hidden="true"></i>Decks Building Guide 2012</p>