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.

Setup

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

<head>
  <!-- other codes ... -->
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.10.2/css/all.min.css">
  <!-- other codes ... -->
</head>


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.

Example

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.

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

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="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script>
    var clicked = false;
    $(document).ready(function() {
        $("#demo").click(function() {
            if (!clicked) {
                $('#myicon').addClass('fa-spinner');
                $('#myicon').addClass('fa-spin'); 
            } else {
                $('#myicon').removeClass('fa-spinner');
                $('#myicon').removeClass('fa-spin');  
            }                   
            clicked = !clicked;    
        });
    });
</script>

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.

References

Font Awesome
The Font Awesome's free spinner icon


Search