How do I make my arrow accordion display a downward pointing arrow when pressed?

Viewed 88

I have created an accordion with an arrow that points right next to it, I would like the arrow to point downwards when clicked on. How would I accomplish this? Should I use images instead of the normal arrow or is it possible to just use the arrow in the way that I used it? Here is my code in jsfiddle: https://jsfiddle.net/homjt76L/2/

var coll = document.getElementsByClassName("collapsible");
var i;

for (i = 0; i < coll.length; i++) {
  coll[i].addEventListener("click", function() {
    this.classList.toggle("active");
    var content = this.nextElementSibling;
    if (content.style.maxHeight){
      content.style.maxHeight = null;
    } else {
      content.style.maxHeight = content.scrollHeight + "px";
    } 
  });
}
h1 {
    text-align: center;
}

.arrow {
    border: solid black;
    border-width: 0 3px 3px 0;
    display: inline-block;
    padding: 3px;
}

.down {
    margin-right: 50px;
    float: left;
    transform: rotate(45deg);
    -webkit-transform: rotate(45);
}

.right {
    margin-right: 50px;
    float: left;
    transform: rotate(-45deg);
    -webkit-transform: rotate(-45deg);
}

.collapsible {
  color: black;
  cursor: pointer;
  padding: 18px;
  width: 100%;
  border: solid thin;
  text-align: left;
  outline: none;
  font-size: 15px;
}

.active, .collapsible:hover {
  background-color: #555;
}

.collapsible:after {
  color: white;
  font-weight: bold;
  float: right;
  margin-left: 5px;
}

.active:after {
}

.content {
  padding: 0 18px;
  max-height: 0;
  overflow: hidden;
  transition: max-height 0.2s ease-out;
  background-color: #f1f1f1;
}
<h1>FAQ</h1>

<button class="collapsible" data-toggle="">
<b>Questions and Answers</b><i class="arrow right"></i>
</button>
<div class="content">
  <p>Lorem Ipsum...</p>
</div>

3 Answers

I would probably rename the right class to indicator and then just add this

.collapsible.active .indicator{
  transform: rotate(45deg);
}

This would mean that you can remove the down class you've written

The indicator class would look like this if you wanted to add a small transition as well

.indicator {
    margin-right: 50px;
    float: left;
    transform: rotate(-45deg);
    transition: 0.2s ease transform;
}

Change icon className right to down on change of className.

Check here: https://jsfiddle.net/Dev024/t4fe6quL/2/

if(this.classList.contains("active"))
{
    this.childNodes[1].className = "arrow right"
}
else
{
    this.childNodes[1].className = "arrow down"
}

You can put a css like this :

.collapsible.active .right:{
    transform: rotate(45deg);
    -webkit-transform: rotate(45deg);
 }
Related