HappyHands31
HappyHands31

Reputation: 4101

Toggle FontAwesome Carets on Click with jQuery

FontAwesome doesn't seem to be loading in the snippets here so please see this JSFiddle:

https://jsfiddle.net/e74coz3f/

What I'm trying to do is initially show the <i class="fas fa-caret-down"></i> on the right side of the div, then switch to show the <i class="fas fa-caret-up"></i> after clicking on the product-suggestion-form-container div. They should switch back and forth between up and down every time you click on the div.

What am I misunderstanding about toggling between active and inactive classes in jQuery?

If I add the active and inactive classes like this to the CSS:

https://jsfiddle.net/c12tvgdj/

nothing shows at all.

Relevant HTML:

<script src="https://use.fontawesome.com/releases/v5.15.1/js/all.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

<div class="product-suggestion-form-container">
  <span class="form-title">Product Suggestion Form</span>
  <span class="dropdown-arrow-top inactive-1"><i class="fas fa-caret-down"></i>
  <span class="dropdown-arrow-up-top active-2"><i class="fas fa-caret-up"></i>
  </span>
</div>

CSS

/*before toggle*/

.product-suggestion-form-container {
  border: 1px solid #c6c6c6;
  padding: 5px 10px;
  display: flex;
  justify-content: space-between;
  background-color: #f8f7f7;
  cursor: pointer;
}

.dropdown-arrow-top {
  display: block;
}

.dropdown-arrow-up-top {
  display: none;
}

/*after toggle*/

.dropdown-arrow-top.inactive-1 {
  /*display: none;*/
}

.dropdown-arrow-up-top.active-1 {
  /*display: block;*/
}

Javascript:

$(document).ready(function(){
   $(".product-suggestion-form-container").click(function(){
      $(".form-div-top").slideToggle();
      $(".dropdown-arrow-top").toggleClass("inactive-1");
      $(".dropdown-arrow-up-top").toggleClass("active-1");
   })
});

Upvotes: 2

Views: 178

Answers (1)

pawel
pawel

Reputation: 557

There are few minor typos in your examples:

  1. In https://jsfiddle.net/e74coz3f/ active-2 is used instead of active-1

  2. In https://jsfiddle.net/c12tvgdj/ second span is not closed and the above problem also exists

Also, jQuery is not correctly installed and I get Uncaught ReferenceError: $ is not defined in JSFiddle console.

Lastly, I think this could be implemented in few simpler ways, e.g. https://jsfiddle.net/c7hwv0a6/1/ or https://jsfiddle.net/a18ju6bv/.

Upvotes: 1

Related Questions