I added to the wish list for products.(django project) Users click on a heart-shaped icon if they add a product to this list. If a user has already added this product to the list, the heart icon is red, and if this product is not in the user's favorites list, the heart icon is white. I want to change the color of the icon each time I remove or add it to the list. In the code I wrote, this operation is done only once, and if it clicks again at the same time, there will be no change in color.
{% if request.user in product.favourite.all %}
<a href="{% url 'home:favourite' product.id %}"
class="favourite-product fa-btn{{ product.id }}"
data-id='{{ product.id }}' data-text="remove">
<i class="fa fa-heart test{{ product.id }}" style="color:red"></i></a>
{% else %}
<a href="{% url 'home:favourite' product.id %}"
class="favourite-product fa-btn{{ product.id }}"
data-id='{{ product.id }}' data-text="add">
<i class="fa fa-heart test{{ product.id }}" style="color:#eee;"></i></a>
{% endif %}
# ajax
$(document).on('click', '.favourite-product', function (e) {
e.preventDefault();
const likeText = $(`.fa-btn${product_id}`).attr("data-text");
const trim = $.trim(likeText)
$.ajax({
url: $(this).attr('href'),
type: 'GET',
data: {
'product': product_id
},
success: function (response) {
if (trim === 'add') {
$(`.test${product_id}`).css({"color": "red"});
} else {
$(`.test${product_id}`).css({"color": "#eee"});
}
},
error: function (response) {
alert("error");
}
});
});