threadr.lostcave.ddnss.de/static/likes.js

52 lines
1.9 KiB
JavaScript

function initLikeButtons() {
document.querySelectorAll('.like-btn, .dislike-btn').forEach(function(btn) {
btn.addEventListener('click', function(e) {
e.preventDefault();
var postId = btn.getAttribute('data-post-id');
var type = btn.getAttribute('data-type');
var basePath = btn.getAttribute('data-base-path');
btn.disabled = true;
var body = new URLSearchParams();
body.append('post_id', postId);
body.append('type', type);
fetch(basePath + '/like/', {
method: 'POST',
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
body: body.toString()
})
.then(function(res) { return res.json(); })
.then(function(data) {
// Find sibling buttons for this post
var article = btn.closest('.post-actions');
var likeBtn = article.querySelector('.like-btn');
var dislikeBtn = article.querySelector('.dislike-btn');
// Update counts
if (likeBtn) {
likeBtn.querySelector('.like-count').textContent = data.likes;
}
if (dislikeBtn) {
dislikeBtn.querySelector('.dislike-count').textContent = data.dislikes;
}
// Update active states
if (likeBtn) {
likeBtn.classList.toggle('active', data.userAction === 'like');
}
if (dislikeBtn) {
dislikeBtn.classList.toggle('active', data.userAction === 'dislike');
}
})
.catch(function(err) {
console.error('Like error:', err);
})
.finally(function() {
btn.disabled = false;
});
});
});
}