Toggle How icon using Javascript

I have aj actuated button and I have defined a function that will update the text. Now I want to change it to upgrade from awesome fa-heart-o to fa-heart and vice versa. How can I do it? see code below

base.html

<script> $(document).ready(function(){ function updateText(btn, newCount, iconClass, verb){ verb = verb || ""; $(btn).html(newCount + '<i class="' + iconClass + '"></i>' + verb ) btn.attr("data-likes", newCount) } $(".like-btn").click(function(e){ e.preventDefault() var this_ = $(this) var likeUrl = this_.attr("data-href") var likeCount = parseInt(this_.attr("data-likes")) | 0 var addLike = likeCount + 1 var removeLike = likeCount - 1 if (likeUrl){ $.ajax({ url: likeUrl, method: "GET", data: {}, success: function(data){ console.log(data) var newLikes; if (data.liked){ updateText(this_, addLike, "fa fa-heart") } else { updateText(this_, removeLike, "fa fa-heart-o") } }, error: function(error){ console.log(error) console.log("error") } }) } }) }) </script> 

and a button like html

 <a class='like-btn' data-href='{{ comentario.get_api_like_url }}' data-likes='{{ comentario.likes.count }}' href='{{ comentario.get_like_url }}'>{{ comentario.likes.count }} {% if request.user in comentario.likes.all %} <i class="fa fa-heart"></i> {% else %} <i class="fa fa-heart-o"></i> {% endif %} 

Thank you for your help.

+5
source share
2 answers

In your success callback, use updateText to define the item.

Example

 success: function(data) { console.log(data) var newLikes; if (data.liked) { updateText(this_, addLike, "fa fa-heart") } else { updateText(this_, removeLike, "fa fa-heart-o") // remove one like } }, error: function(error) { console.log(error) console.log("error") } function updateText(btn, newCount, iconClass, verb) { verb = verb || ""; $(btn).html(newCount + '<i class="fa' + iconClass + '"></i>' + verb) btn.attr("data-likes", newCount) } 
+2
source

enter image description here

here is the image on the screen, the class is similar to -btn

+1
source

Source: https://habr.com/ru/post/1276281/


All Articles