Share Counter | Download Counter for Blogger
Finally I have created a share counter or Download Counter for blogger blogspot.
by thvinic
HTML
<script src="https://www.gstatic.com/firebasejs/4.8.1/firebase.js"></script>
<script src="https://www.gstatic.com/firebasejs/4.8.1/firebase-database.js"></script>
<div class='post post-test uk-padding uk-text-center' id='post-139513502350'>
<h4>Post Title 1</h4>
<p>Share count: <a class="count">0</a></p>
<button type="button" class="like">Like</button>
</div>
<div class='post post-test uk-padding uk-text-center' id='post-144444444440'>
<h4>Post Title 2</h4>
<p>Share count: <a class="count">0</a></p>
<button type="button" class="like">Like</button>
</div>
<div class='post post-test uk-padding uk-text-center' id='post-155555555550'>
<h4>Post Title 3</h4>
<p>Share count: <a class="count">0</a></p>
<button type="button" class="like">Like</button>
</div>
JavaScript
// Initialize Firebase
var config = {
apiKey: "AIzaSyAPUlB0CgQSoqbNBLvGwD42LPb8tm_7Rgs",
authDomain: "classificados-anunciarbr.firebaseapp.com"
};
firebase.initializeApp(config);
// Get a reference to the database service
var database = firebase.database();
$('.post-test').each(function() {
var $this = $(this),
postId = $this.attr('id'),
setData = database.ref('likecounter/posts/' + postId).child('count');
var data = {},
isnew = false;
setData.once('value').then(function(snapshot) {
data = snapshot.val();
if (data == null) {
data = {};
data = 0;
isnew = true;
}
var newValue = data;
if (data >= 1000) {
var suffixes = ["", "K", "M", "B","T"];
var suffixNum = Math.floor( (""+data).length/3 );
var shortValue = '';
for (var precision = 2; precision >= 1; precision--) {
shortValue = parseFloat( (suffixNum != 0 ? (data / Math.pow(1000,suffixNum) ) : data).toPrecision(precision));
var dotLessShortValue = (shortValue + '').replace(/[^a-zA-Z 0-9]+/g,'');
if (dotLessShortValue.length <= 2) { break; }
}
if (shortValue % 1 != 0) shortNum = shortValue.toFixed(1);
newValue = shortValue+suffixes[suffixNum];
}
$this.find('.count').html(newValue);
});
$this.find('.like').on('click', function() {
data++;
if (isnew) setData.set(data);
else setData.set(data);
$this.find('.count').html(data);
});
});