Search code examples
javascriptjqueryfont-awesomefont-awesome-5

jQuery issue with replacing Font Awesome 5 icon on click?


I am trying to change a play button to be a pause button using Font Awesome 5. I don't understand why it seems to just not toggle on click. It recognizes the clicks (I tried with an alert, so it recognizes when I press the button itself) but it will just not find the element inside and change it.

This is my code:

$(".startButton").click(function() {
  $(this).find("i").removeClass("fa-play-circle").addClass("fa-pause-circle")
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<head>
  <script defer src="https://use.fontawesome.com/releases/v5.0.6/js/all.js"></script>
</head>

<div id="timerWrapper">
  <div class="valuesWrapper">
    <div class="values"> 00:00:00</div>
  </div>
  <div id="buttonWrapper">
    <button class="startButton"><i class="fas fa-play-circle"></i></button>
    <button class="stopButton">Stop</button>
    <button class="clearButton">Clear</button>
  </div>
</div>


Solution

  • The main issue with your code is that you are using Font Awesome 5 that changes the i element to svg so your code won't work.

    You have two solution:

    The easiest one is to use the CSS version of Font Awesome 5 and you will be able to keep your code as it is:

    $(".startButton").click(function() {
      $(this).find("i").removeClass("fa-play-circle").addClass("fa-pause-circle");
    });
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <link href="https://use.fontawesome.com/releases/v5.2.0/css/all.css" rel="stylesheet">
    <div id="timerWrapper">
      <div class="valuesWrapper">
        <div class="values"> 00:00:00</div>
      </div>
      <div id="buttonWrapper">
        <button class="startButton"><i class="fas fa-play-circle"></i></button>
        <button class="stopButton">Stop</button>
        <button class="clearButton">Clear</button>
      </div>
    </div>

    The other solution is to change your code in order to handle the SVG. So you may change the data-icon attribute of the generated svg with the needed icon:

    $(".startButton").on('click',function() {
      $(this).find('svg').attr("data-icon",'pause-circle');
    });
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <script defer src="https://use.fontawesome.com/releases/v5.2.0/js/all.js"></script>
    <div id="timerWrapper">
      <div class="valuesWrapper">
        <div class="values"> 00:00:00</div>
      </div>
      <div id="buttonWrapper">
        <button class="startButton"><i class="fas fa-play-circle"></i></button>
        <button class="stopButton">Stop</button>
        <button class="clearButton">Clear</button>
      </div>
    </div>