How can I dynamically create a tweet button?

Jack picture Jack · Aug 8, 2011 · Viewed 10.8k times · Source

I'm currently trying to create a tweet button with the horizontal count feature dynamically:

JavaScript

var twitter = document.createElement('a');
twitter.setAttribute('href', 'http://twitter.com/share');
twitter.setAttribute('class', 'twitter-share-button twitter-tweet');
twitter.setAttribute('data-url','http://mindcloud.co.uk/idea/?idea=' + this.id);
twitter.setAttribute('data-count', 'horizontal');
twitter.setAttribute('data-via', 'jtbrowncouk');
twitter.style.top = '20px';
twitter.style.left = '300px';
twitter.innerHTML = "Tweet";

The problem i'm having is that the button is being displayed as a text link, not as a button with the horizontal count box.

I've created a facebook button in the same way, which works correctly, however to make it work I use the following:

JavaScript

var facebook = document.createElement('fb:like');
facebook.setAttribute('id', 'like'+this.id);
facebook.setAttribute('href', 'http://mindcloud.co.uk/idea/?idea=' + this.id);    
facebook.setAttribute('layout', 'button_count');
facebook.setAttribute('send', 'false');        
facebook.setAttribute('width' , '300');
facebook.setAttribute('font', '');
facebook.setAttribute('show_faces', 'true');
facebook.style.top = '0px';
facebook.style.left = '300px';

using the following:

FB.XFBML.parse();

to parse and draw the button. FB.XFBML.parse() comes from http://connect.facebook.net/en_US/all.js

When I create the Tweet button statically inside a .html file it works correctly. I'm including the following script within my index page where the tweet button should be created dynamically:

<script type="text/javascript" src="http://platform.twitter.com/widgets.js"></script>

If you can see what i'm doing incorrectly please inform me!

The following screenshot gives a visual explanation to what is going wrong with the tweet button! Tweet button not displaying correctly.

Solution:

I've now managed to solve the problem. The problem i'd imagine is that the twitter script is running on load, and not being re-run upon creating the element.

using the following jQuery works correctly!

$.getScript("http://platform.twitter.com/widgets.js");

Answer

dougajmcdonald picture dougajmcdonald · Apr 2, 2012

It's worth noting that as of recently you can use the following twitter widget function:

twttr.widgets.load();

Assuming you've loaded the widgets.js file:

<script type="text/javascript" src="http://platform.twitter.com/widgets.js"></script>

This will dynamically re-create the tweet button for you.