How to usetoggleClass() Method in JQuery

This approach creates a like button using HTML and jQuery. When clicked, it toggles a “liked” class, changing the text and color to represent the like/unlike state.

Syntax

$(selector).toggleClass(classname)

Example: In this example, we are using a Font Awesome heart icon inside a button element. jQuery’s toggleClass method switches between classes, changing the heart’s color from black to red and style from regular to solid when the button is clicked, simulating Instagram’s like button.

HTML




<!DOCTYPE html>
<html>
  
<head>
    <link rel="stylesheet" 
          href=
"https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.2/css/all.min.css" />
    <script src=
"https://code.jquery.com/jquery-3.7.1.min.js">
    </script>
    <style>
        button {
            background-color: transparent;
            border: none;
        }
  
        .fa-heart {
            font-size: 25px;
  
        }
  
        .blank {
            color: #142034;
        }
  
        .red {
            color: red;
        }
    </style>
</head>
  
<body>
    <h2 style="color: green;">
        Welcome To GFG
    </h2>
    <p>
        Instagram Like Button using toggleClass
    </p>
  
    <button id="like">
        <i id="icon" 
           class="fa-regular fa-heart blank">
        </i>
    </button>
  
    <script>
        $(document).ready(function () {
            $("#like").on("click", function () {
                $("#icon").toggleClass("red");
                $("#icon").toggleClass("fa-solid");
            });
        });
    </script>
</body>
  
</html>


Output:

How to Create Instagram Like Button in jQuery ?

In this article, we will learn how to create an Instagram-like button using jQuery. An Instagram Like button is a user interface element that, when clicked, signifies appreciation or approval for a post. It often features a heart icon and toggles between filled (liked) and outlined (unliked) states.

There are several methods that can be used to create an Instagram Like button in jQuery, which are listed below:

Table of Content

  • Using toggleClass()
  • Using if-else() Conditions

We will explore all the above methods along with their basic implementation with the help of examples.

Similar Reads

Approach 1: Using toggleClass() Method

...

Approach 2: Using if-else Conditions

This approach creates a like button using HTML and jQuery. When clicked, it toggles a “liked” class, changing the text and color to represent the like/unlike state....