Tech Note: Creating Tweet Buttons Dynamically
As I mentioned yesterday, I’ve integrated Twitter’s new official “Tweet Button” into the LGF Blog code to see how it compares to our previous Tweet button/retweet count feature, which calls the API at bit.ly to get the count statistics.
But I ran into a problem with the Twitter code: it’s intended to work only on page load, and there’s no documented way to dynamically add Tweet Buttons to content generated via Ajax. This meant I couldn’t add Tweet Buttons to the articles that appear when you click the “Show More Articles” button at the bottom of the LGF front page.
So I took a look at Twitter’s Javascript code for generating the buttons, which is located here. It’s “minified,” so I ran it through the Javascript unpacker and beautifier first, then read through the code (it’s pretty short) and discovered that installing a Tweet Button is a simple matter of instantiating a “TweetButton” object (passing it the DOM object — not the jQuery object — for the link that will be turned into a button), then calling the TweetButton’s “render” method.
The code to do this dynamically via jQuery is surprisingly simple. (The variable “thediv” is the container for the newly loaded articles.)
$(thediv).find('a.twitter-share-button').each(function(i) {
var thisTweetButton = new twttr.TweetButton($(this).get(0));
thisTweetButton.render();
});
A sidenote: I’ve noticed that the official Tweet Button is reporting lower numbers for the retweet count than bit.ly’s API does. It’s not immediately apparent why there’s a discrepancy.