How to useif-else Conditions in JQuery

In this approach, we are making an Instagram-like button with Font Awesome heart icons. Upon clicking, it alternates between regular and solid heart styles, with color changes. The behavior is managed using jQuery.

Syntax

if (condition1) {
} else if (condition2) {
} else {
}

Example: In this example we are using above-explained approach.

HTML




<!DOCTYPE html>
<html>
  
<head>
    <link rel="stylesheet" 
          href=
"https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.2/css/all.min.css"
        integrity=
"sha512-z3gLpd7yknf1YoNbCzqRKc4qyor8gaKU1qmn+CShxbuBusANI9QpRohGBreCFkKxLhei6S9CQXFEbbKuqLg0DA=="
        crossorigin="anonymous" 
        referrerpolicy="no-referrer" />
        <script src=
"https://code.jquery.com/jquery-3.7.1.js"
        integrity=
"sha256-eKhayi8LEQwp4NKxN+CfCh+3qOVUtJn3QNZ0TciWLP4=" 
        crossorigin="anonymous">
    </script>
    <title>Welcome To GFG</title>
    <Style>
        h2 {
            color: green;
        }
  
        button {
            background-color: transparent;
            border: none;
        }
  
        .fa-heart {
            font-size: 40px;
        }
    </Style>
</head>
  
<body>
    <h2>Welcome To GFG</h2>
    <p>
        Instagram Like Button
    </p>
    <div class="hello">
        <button id="like">
            <i class="fa-regular fa-heart"></i>
        </button>
    </div>
      
    <script>
        $(document).ready(function () {
            let lv = 0;
            $("#like").on("click", function () {
  
                if (lv == 0) {
                    $('#like').html(
                        '<i class="fa-regular fa-heart"></i>');
                    lv = 1;
                } else {
                    $('#like').html(
                        '<i class="fa-solid fa-heart" style="color: #f52e4b;"></i>');
                    lv = 0
                }
            });
        });
    </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....