简体   繁体   中英

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> 

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> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM