Skip to content
Related Articles

Related Articles

How to toggle between two icons without buttons using boot-strap and jQuery ?
  • Last Updated : 18 Jan, 2021

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 the 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

filter_none

edit
close

play_arrow

link
brightness_4
code

<!DOCTYPE html>
<html lang="en">
  
<head>
    <meta charset="UTF-8" />
    <meta name="viewport" content=
        "width=device-width,initial-scale=1.0" />
  
    <!--Bootstrap CSS CDN-->
    <link rel="stylesheet" href=
        integrity=
"sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm"
        crossorigin="anonymous" />
  
    <!--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>

chevron_right


Output:

full-stack-img




My Personal Notes arrow_drop_up
Recommended Articles
Page :