Thursday, 30 July 2020

How to use the Font Awesome's spinner icon in JavaScript

jQuery  JavaScript  Font Awesome 

Font Awesome provides free icons for web development. We can use its spinner icons on a web page to indicate a work or operation is in process.


The setup for Font Awesome is simple. Inside the head section of a web page, include the reference for its CSS file.

  <!-- other codes ... -->
  <link rel="stylesheet" href="">
  <!-- other codes ... -->

How to Use

We can use a Font Awesome icon with a <i> tag and place it anywhere you want on a web page.

<i class="fas fa-spinner"></i>

fas is the style prefix and it is the Font Awesome's free Solid style. fa-spinner is the icon's name.


This example shows how to make the Font Awesome's spinner icon spin when the button is clicked on a web page.

First, we place a button on a web page.

  <!-- other codes ... -->
  <button type="button" id="demo" >demo
  <i id="myicon" class="fas"></i></button>
  <!-- other codes ... -->

In line 4, we use class="fas" to define that we are using the Font Awesome's Solid style icons (the free ones). Since we don't put the icon's name fa-spinner in the class attribute, the spinner icon doesn't show yet.

Then, we need jQuery to handle the button click event and make the Font Awesome spinner icon to spin and stop by changing the spinner icon's class attribute.

<script src=""></script>
    var clicked = false;
    $(document).ready(function() {
        $("#demo").click(function() {
            if (!clicked) {
            } else {
            clicked = !clicked;    

In line 1, we reference the jQuery library. In line 3, we define a variable var clicked to remember whether the button is clicked or not. If the button is clicked at the first time (from line 7 to line 8), the icon will be shown on the button by adding the icon's name "fa-spinner" in the class attribute. The class name "fa-spin" is also added for making the icon to spin. If the button is clicked again (from line 10 to line 11), relevant classes ("fa-spinner" and "fa-spin") will be removed from the class attribute and the spinning icon will stop and disapear.


Font Awesome
The Font Awesome's free spinner icon