1

$('.like-btn').click((e) => {
  e.target.classList = 'like-unlike-btn unlike-btn far fa-heart';
});

$('.unlike-btn').click((e) => {
  e.target.classList = 'like-unlike-btn like-btn far fa-heart';
});
.like-unlike-btn {
  color: #fb3958;
  font-size: 2rem;
  position: absolute;
  top: 0;
  left: 10px;
  cursor: pointer;
}

.like-unlike-btn:hover {
  color: rgb(252, 11, 11);
}

.unlike-btn {
  font-weight: bold;
}

.like-btn {
  font-weight: normal;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.3.1/css/all.css"
    integrity="sha384-mzrmE5qonljUremFsqc01SB46JvROS7bZs3IO2EmfFsd15uHvIt+Y8vEf7N7fWAU" crossorigin="anonymous">

<i class="like-unlike-btn like-btn far fa-heart"></i>

Why is my code is not working? The first click event is working fine but the second is not working Please suggest some other ways to do it.

Zakaria Acharki
  • 66,747
  • 15
  • 75
  • 101

1 Answers1

0

You can attach the event to the main class like-unlike-btn and use toggleClass instead :

$('.like-unlike-btn').on('click', function(e) {
  $(this).toggleClass('unlike-btn like-btn');
});
.like-unlike-btn {
  color: gray;
  font-size: 2rem;
  position: absolute;
  top: 0;
  left: 10px;
  cursor: pointer;
}

.like-unlike-btn:hover {
  color: red !important;
}

.like-btn {
  color: red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.3.1/css/all.css" integrity="sha384-mzrmE5qonljUremFsqc01SB46JvROS7bZs3IO2EmfFsd15uHvIt+Y8vEf7N7fWAU" crossorigin="anonymous">

<i class="like-unlike-btn like-btn far fa-heart"></i>
Zakaria Acharki
  • 66,747
  • 15
  • 75
  • 101