I have a like button that is part of a form that uses a javascript function. The function seems to work as intended (adding or subtracting a like from the like count) so it must be changing the class of the button but it won't update the styling unless i refresh the page. I want the styling to turn the button background white when it is liked and transparent when not liked.
Script:
$(document).ready(function() {
$('.like_form').submit(function(e){
e.preventDefault()
const post_id = $(this).attr('id')
console.log(post_id)
const url = $(this).attr('action')
let res;
const likes = $(`.like_count${post_id}`).text()
const trimCount = parseInt(likes)
console.log(trimCount + 1)
var element = document.getElementById("like_button");
$.ajax({
type: 'POST',
url: url,
data: {
'csrfmiddlewaretoken': $('input[name=csrfmiddlewaretoken]').val(),
'post_id': post_id,
},
success: function(response){
if (element.classList.contains("liked_post")){
res = trimCount - 1
element.classList.remove("liked_post")
} else if (!$(this).hasClass("liked_post")) {
res = trimCount + 1
element.classList.add("liked_post")
}
$(`.like_count${post_id}`).text(res +' Likes')
},
error: function(response){
console.log('error', response)
}
})
})
});
form:
<form action="{% url 'like_post' item.id %}" class="like_form" id="{{ item.id }}">
{% csrf_token %}
{% if user in item.likes.all %}
<button type="submit" class="like_btn liked_post" name="post_id" value="{{ item.id }}"><div class="liked_btn" id="like_button">Like</div></button>
{% else %}
<button type="submit" class="like_btn" name="post_id" value="{{ item.id }}"><div class="liked_btn" id="like_button">Like</div></button>
{% endif %}
</form>