I'd like to include a "like" button on a website with a counter. The like buttons include a tally for the current number of likes. If it is not clicked, the current number of likes is displayed. When a button is clicked, the current number of clicks is increased by one (and the button's state or appearance changes), and the like count should be stored on server-side logic to store and serve the number of likes.
Is it possible to achieve this in HTML, CSS, and Jquery?
Use this code snippet :)
let likes = 0;
$(document).ready(function () {
// ajax to get current likes
// let likes from server are 10
// assign the current likes to variable
likes = 10;
setLikes(likes);
});
$("body").on("click", ".likeBtn", function () {
// ajax to post a current likes
// in success add increment to likes
likes++;
setLikes(likes);
});
function setLikes(count) {
$(".totalLikes").text(count);
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Likes Counter</title>
</head>
<body>
<button class="likeBtn">
Like (<span class="totalLikes">0</span>)
</button>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</body>
</html>