I have a post view counter (Blogger) which is connected to a Firebase database and is working fine. But I would like to add the like counter to the same database and structure for each post id.
Postviews js
<script> $.each($("a[name]"), function(i, e) { var elem = $(e).parent().find("#postviews"); var blogStats = new Firebase("My-Project-URL/pages/id/" + $(e).attr("name")); blogStats.once("value", function(snapshot) { var data = snapshot.val(); var isnew = false; if(data == null) { data= {}; data.value = 0; data.url = window.location.href; data.id = $(e).attr("name"); isnew = true; } elem.text(data.value); data.value++; if(window.location.pathname!="/") { if(isnew) blogStats.set(data); else blogStats.child("value").set(data.value); } }); }); </script>
Show the views value
<i class='fa fa-eye'/> <a expr:name='data:post.id'/><span id='postviews'/> Views
Like counter js
<script>
// store the main Firebase URL
var firebaseURL = 'My-Project-URL/pages/id/';
// update the likeCounts shown in a <span> beside each blogpost
var postDivs = document.querySelectorAll('.post');
for (var i = 0; i < postDivs.length; i++) {
var postID = postDivs[i].id;
var numLikes = getLikeCount(postID);
}
// this function grabs the likeCount for a particular post from the Firebase
function getLikeCount(postID) {
console.log('running getLikeCount for post ID:', postID);
var thisPostRef = new Firebase(firebaseURL + postID + '/like-count/');
thisPostRef.once('value', function(snapshot) {
console.log( postID + ' value:', snapshot.val() );
if ( snapshot.val() ) {
console.log( postID + ' contains:', snapshot.val() );
document.querySelector('#' + postID + ' .like-count').innerHTML = snapshot.val() + ' likes';
} else {
console.log( postID + '- no data in Firebase' );
return 0;
}
});
}
function likePost(id) {
console.log('running likePost() for post ID:', id);
var postRef = new Firebase(firebaseURL + id);
// get current number of likes here, so we can increment if any exist
postRef.child('like-count').once('value', function(snapshot){
console.log( 'snapshot.val():', snapshot.val() );
var currentLikes = snapshot.val() ? snapshot.val() : 0;
console.log( 'currentLikes:', currentLikes );
postRef.update({
'postID': id,
'like-count': currentLikes + 1
}, function(error) {
if (error) {
console.log('Data could not be saved:' + error);
} else {
console.log('Data saved successfully');
}
});
getLikeCount(id);
});
}
</script>
Show the likes value:
<a expr:name='data:post.id'/> <button onclick='likePost()'> <i class='fa fa-thumbs-up' style='font-size:36px'/></button> <span id='likes'/>
I tried to get the post id but always have to put it manually on the onlick=’likePost()’ function to get something stored in the database.
I don’t know how to integrate the like counter code to the viewpost code (which is working) and have same database structure.