Open In App

How to toggle between two icons without buttons using jQuery?

Last Updated : 08 Jul, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

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, 

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

Whenever a user clicks 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: This example shows the implementation of the above-mentioned approach.

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-->
    <script src=
"https://kit.fontawesome.com/f2c150d561.js"
        	crossorigin="anonymous">
        </script>

    <!--jQuery CDN-->
    <script src="https://code.jquery.com/jquery-3.2.1.slim.min.js"
        	integrity=
"sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN"
	        crossorigin="anonymous">
        </script>
</head>

<body>
    <!--First Icon-->
    <i class="fas fa-bars" style="font-size: 60px;"></i>

    <script>
        $(".fas").click(function () {
            $(".fas").toggleClass("fa-bars fa-times");
        }); 
    </script>
</body>

</html>

Output:

Toggle between two icons


Next Article

Similar Reads