Skip to content
Related Articles
Open in App
Not now

Related Articles

How to toggle between two icons without buttons using jQuery ?

Improve Article
Save Article
Like Article
  • Last Updated : 23 Feb, 2023
Improve Article
Save Article
Like Article

Given an HTML document with two icons, the task is to alternatively display the icons each time when a user clicks on the icon. This task can be easily accomplished with the help of jQuery (A JavaScript library).

Approach: The approach is to simply add an “on click” event listener to both of the icons and toggle the CSS classes of both icons using jQuery. These classes are ultimately responsible for displaying a specific icon from the icon library (Fontawesome, in this case). Here, we have used two icons, 

  1. One with the class name of “fa-bars” (Menu icon)
  2. One with the class name of “fa-times” (Cross icon)

Whenever a user will click on the menu icon, its “fa-bars” class will be toggled to “fa-times”, thus the cross icon will be then displayed and vice versa is also true. 

 

Example:

HTML




<!DOCTYPE html>
<html lang="en">
  
<head>
    <meta charset="UTF-8" />
    <meta name="viewport" content=
        "width=device-width,initial-scale=1.0" />
  
    <!--Font Awesome Icons-->
        crossorigin="anonymous">
    </script>
      
    <!--jQuery CDN-->
        integrity=
"sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN"
        crossorigin="anonymous">
    </script>
</head>
  
<body>
    <!--First Icon-->
    <i class="fas fa-bars m-5" style="font-size: 60px;"></i>
      
    <script>
        $(".fas").click(function () {
            $(".fas").toggleClass("fa-bars fa-times");
        });
    </script>
</body>
  
</html>


Output:

Toggle between two icons


My Personal Notes arrow_drop_up
Like Article
Save Article
Related Articles

Start Your Coding Journey Now!