Skip to content

Instantly share code, notes, and snippets.

@acoyfellow
Last active October 4, 2017 06:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save acoyfellow/a54bad81c0c87a310f5b to your computer and use it in GitHub Desktop.
Save acoyfellow/a54bad81c0c87a310f5b to your computer and use it in GitHub Desktop.
A simple website counter that tracks website hits in real-time, uses Firebase
'use strict';
(function() {
var Firebase = require('firebase'),
Database = new Firebase('https://sendgrowth-counter.firebaseio.com/'),
pageURL = document.URL.split('.').join('_'),
pageURL = pageURL.split('/').join('*'),
domain = window.location.host,
rootRef = null,
pagePref='one',
labelPref,
locPref,
choice,
scripts = document.getElementsByTagName('script'),
scriptLoc;
for(var i = 0, l = scripts.length; i < l; i++){
if(scripts[i].id === 'counter'){
pagePref = scripts[i].getAttribute('page');
labelPref = scripts[i].getAttribute('label');
locPref = scripts[i].getAttribute('loc');
break;
};
};
if(pagePref=='one'){
rootRef = Database.child(pageURL.split('.').join('_'));
}else{
rootRef = Database.child(domain.split('.').join('_'));
};
rootRef.transaction(function(currentData) {
if (currentData === null) {
var obj = {total: 1 };
obj[pageURL] = {total: 1};
return obj;
} else {
if (currentData[pageURL] === null){
var obj = { total: currentData.total+1 };
obj[pageURL] = {total: 1};
return obj
}else{
var obj = {total: currentData.total+1 };
obj[pageURL] = {total: currentData[pageURL].total+1};
return obj
};
}
}, function(error, committed, snapshot) {
if (error) {
return false;
} else if (!committed) {
return false;
}
insert_counter(snapshot);
});
function insert_counter(snapshot){
choice=choice.toLocaleString();
if(pagePref==='all'){ choice = snapshot.val().total };
if(pagePref==='one'){ choice = snapshot.val()[pageURL].total };
var element = document.createElement('div'), css;
css = 'padding:5px;margin:5px;z-index: 99999;background: lightblue; text-align:center;';
if(locPref==='float'){ css = css+'position:fixed;bottom: 0;left: 0;' };
element.style.cssText = css;
element.innerHTML = labelPref+' <b>'+choice+'</b>';
var location = document.getElementById('counter');
location.parentNode.insertBefore(element, location);
rootRef.on('value', function(dataSnapshot) {
if(pagePref==='all'){ choice = dataSnapshot.val().total };
if(pagePref==='one'){ choice = dataSnapshot.val()[pageURL].total };
element.innerHTML = labelPref+' <b>'+choice+'</b>';
});
};
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment