RP12
RP12

Reputation: 428

How can I make my icon toggle using jQuery and MaterializeCSS?

In MaterializeCSS there is a specific syntax to calling their premade icons. This is an example:

<i class="material-icons">expand_more</i>

The framework knows what icon you want based on the text between the i tags. I am trying to create a collapsible div using jQuery and I would like for the icon to flip between an up and down arrow. In order to do this, I need to replace the text in between the i tags.

I am successfully able to change it once but not back when I collapse the div. Here is my code:

$('.remove-text').click(function() {
  $(this).closest('.card').toggleClass('collapsed');
  if ($('.arrow-change').text = 'expand_more') {
    $('.arrow-change').text('expand_less');
  } else {
    $('.arrow-change').text('expand_more');
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="remove-text">
  <i class="material-icons arrow-change">expand_more</i>
</div>

Upvotes: 0

Views: 1141

Answers (3)

Try with this:

$('.remove-text').click(function() {

var parent_child = $(this);

parent_child.toggleClass('collapsed');

if(parent_child.hasClass('collapsed')){
    parent_child.children('i.arrow-change').text('expand_less');
}else{
    parent_child.children('i.arrow-change').text('expand_more');
}

});

Example: https://jsfiddle.net/r5152vna/

Upvotes: 0

SrAxi
SrAxi

Reputation: 20005

Try using this slideToggle()

$( "#collapsibleDiv" ).slideToggle( "slow", function() {
// Animation complete.

});

Here is my plunkr

Upvotes: 0

Waxi
Waxi

Reputation: 1651

Your use of = is actually setting the value, what you actually want is == or === which is a comparison.

The double equals doesn't enforce type match, but the triple does.

Also, it's text(), not just text, because you're using jQuery. If you wanted to use vanilla, it would be innerText.

Upvotes: 3

Related Questions