I have made a like button powered by ajax and I have defined a function that it refresh the text. Now I want to change it for updating from font awesome fa-heart-o to fa-heart and viceversa. How can I do it? see the 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 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.
In your success callback, use updateText to define the element.
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)
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With