forked from openaustralia/theyvoteforyou
-
Notifications
You must be signed in to change notification settings - Fork 1
/
shareCount.js
98 lines (87 loc) · 2.65 KB
/
shareCount.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
// Get the number of shares on twitter and facebook and add it to the page
// inspired by and built upon share-count.js by the Guardian team
// https://github.com/guardian/frontend/blob/master/static/src/javascripts/projects/common/modules/social/share-count.js
var shareCount = 0,
$shareLabel = $('.social-share-heading'),
$shareCountEls = $('.js-sharecount'),
page = window.location.protocol + "//" + window.location.host + window.location.pathname,
counts = {
facebook: 'n/a',
twitter: 'n/a'
};
$sharesNoun = "shares";
if ($shareLabel.attr('data-shares-noun') != undefined) {
$sharesNoun = $shareLabel.attr('data-shares-noun');
}
function updateShareText() {
if ($shareLabel.contents().last() !== (" " + $sharesNoun)) {
$shareLabel.contents().last().remove();
$shareLabel.append(" " + $sharesNoun);
}
}
function updateTooltip() {
var tooltip = 'Facebook: ' + counts.facebook + '\nTwitter: ' + counts.twitter;
$shareCountEls.attr('title', tooltip);
}
function addToShareCount(val) {
if (val !== 0) {
$shareCountEls.addClass("js-sharecount-active");
var hasRun = false;
var queries = [
{
context: 'small',
match: function() {
if (hasRun === false) {
incrementShareCount(val);
hasRun = true;
}
}
},
{
context: 'wide',
match: function() {
if (hasRun === false) {
var duration = 250,
updateStep = 25,
slices = duration / updateStep,
amountPerStep = val / slices,
currentSlice = 0,
interval = window.setInterval(function () {
incrementShareCount(amountPerStep);
if (++currentSlice === slices) {
window.clearInterval(interval);
}
}, updateStep);
hasRun = true;
}
}
}
];
MQ.init(queries);
updateTooltip();
updateShareText();
}
}
function incrementShareCount(amount) {
if (amount !== 0) {
shareCount += amount;
var displayCount = shareCount.toFixed(0);
$shareCountEls.text(displayCount);
}
}
function getShareCounts() {
if ($shareCountEls.length) {
facebook_url = "https://graph.facebook.com/?ids=" + page +"&callback=?";
twitter_url = "https://cdn.api.twitter.com/1/urls/count.json?url=" + page + "&callback=?";
$.getJSON(facebook_url, function(data) {
var count = data[page].shares || 0;
counts.facebook = count;
addToShareCount(counts.facebook);
});
$.getJSON(twitter_url, function(data) {
var count = data.count || 0;
counts.twitter = count;
addToShareCount(counts.twitter);
});
}
}