How to dynamically create Twitter’s tweet button and Facebook’s like button!

I just came across a requirement where I had to create Twitter’s tweet button and Facebook’s like button on the fly.

Doing so is pretty trivial!

Creating the tweet button dynamically

The first thing to do would be to include http://platform.twitter.com/widgets.js.

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

Now consider an example where you have made an ajax request and the response consists of html with links having the class twitter-share-button:

<a href="http://twitter.com/share" class="twitter-share-button">Tweet</a>

Following is how you would go about creating the tweet buttons dynamically:

$.get('ajax/test.html', function(html)
{
	var $response = $( html );

	// if there is an empty response do nothing
	if( $response.length < 1 ) return;

	// create the twitter buttons
	$response.find('a.twitter-share-button').each(function()
	{
		var tweet_button = new twttr.TweetButton( $( this ).get( 0 ) );
		tweet_button.render();
	});
});

Creating the fb like button dynamically

The first thing to do would be including the fb sdk as follows:

<div id="fb-root"></div>
<script>
window.fbAsyncInit = function()
{
     FB.init({appId: 'your app id', status: true, cookie: true, xfbml: true});
};   

(function() {
     var e = document.createElement('script');
     e.async = true;
     e.src = document.location.protocol +  '//connect.facebook.net/en_US/all.js';
     document.getElementById('fb-root').appendChild(e);
}());
</script>

Lets again consider the example where you make an ajax request and the response consists of fb like tags, something like following:

<div class="share_button btn_fb">
	<fb:like layout="button_count" font="tahoma"></fb:like>
</div>

Following is how you would go about creating the fb like button dynamically:

$.get('ajax/test.html', function(html)
{
	var $response = $( html );

	// if there is an empty response do nothing
	if( $response.length < 1 ) return;

	// create the facebook buttons
	$response.find('.btn_fb').each(function()
	{
		FB.XFBML.parse( this );
	});
});

Although creating these social button is trivial, but I guess the js sdks should have been documented more properly!

  • http://askznatrainer.com/about/twitter-updates-for-2010-11-04 Twitter Updates for 2010-11-04 |

    [...] How to dynamically create Twitter's tweet button and Facebook's … [...]

  • http://www.worldspinner.us/twitter World Spinner

    How to dynamically create Twitter's tweet button and Facebook's ……

    Here at World Spinner we are debating the same thing……

  • http://blog.cyberwealthzone.com/?p=7382 Office Quotes | CyberWealthZone Blog

    [...] How to dynamically create Twitter's tweet button and Facebook's … [...]

  • http://frankkern.welcometomarketing.com/sponsored-tweets-how-to-get-celebrities-promoting-your-business-opportunity Sponsored Tweets: How To Get Celebrities Promoting Your Business Opportunity! | Welcome To Marketing

    [...] How to dynamically create Twitter's tweet button and Facebook's … [...]

  • http://topsy.com/www.ovaistariq.net/447/how-to-dynamically-create-twitters-tweet-button-and-facebooks-like-button/?utm_source=pingback&utm_campaign=L2 Tweets that mention How to dynamically create Twitter’s tweet button and Facebook’s like button! | ovais.tariq — Topsy.com

    [...] This post was mentioned on Twitter by Dave Larson and News, Status & T, Ovais Tariq. Ovais Tariq said: How to dynamically create Twitter’s tweet button and Facebook’s like button! | ovais.tariq http://t.co/RCdca5M via @ovaistariq #javascript [...]

  • http://brandwaffle.myopenid.com/ Vasken

    Thank you for this awesome article!!! I just used part of the Twitter code you posted above to get async loading of Tweet Buttons working perfectly on ajax requests. It’s worth pointing out that I was actually unable to control the ajax call, so the code above wouldn’t have worked as is, but it was easily modified into this (re-renders Twitter and Facebook sharing links):

    $(‘.topic-term-link’).ajaxComplete(function(){
    FB.XFBML.parse(document.getElementById(‘content’));

    $(‘#content’).find(‘a.twitter-share-button’).each(function(){
    var tweet_button = new twttr.TweetButton( $( this ).get( 0 ) );
    tweet_button.render();
    });
    });

    Since jQuery lets me bind directly to the ajaxComplete event, I didn’t even need control over the Ajax call, which is good, because it wasn’t an option. Thanks again for this code. Now, maybe Twitter will name the main function in widgets.js and we can just call a single line like for Facebook in the above example.

    Thank you so much for posting this! I’d been searching for a workaround for hours, and this is the only one that’s elegant and as efficient as possible, given what it has to do.

  • http://neverblog.net/refresh-twitter-and-facebook-social-icons-after-an-ajax-request/ Refresh Twitter and Facebook social icons after an Ajax request « neverblog.net

    [...] I found this post, which outlined the best workaround I’d seen yet for interacting with Twitter’s [...]

  • http://www.ovaistariq.net/ Ovais Tariq

    Its nice to know that I helped you out,.

  • http://aurimas.eu Anonymous

    Hi, your code is awesome. Saved my day for Twitter button. However, I still have a Google Buzz button that I need to create on the fly, too. Any ideas how to dig up the functions for this task?

  • http://www.ovaistariq.net/ Ovais Tariq

    well let me find out,.

  • http://pulse.yahoo.com/_2UWKLFZSQSK6SBSI3EPKCL6FVM William Hawker

    twttr.TweetButton(DOMElem) seems to have broken since the introduction of the Follow button (yesterday). Firebug tells me twttr.TweetButton is not a constructor.Has anyone figured out how to fix this?

  • http://twitter.com/3advance Paul Murphy

    Getting that same Javascript error across browsers… any ideas anyone? Looking into it myself too.

  • http://tobias-seckinger.de/2011/06/twitter-tweet-button-nach-ajax-request-nachladen/ Twitter Tweet Button nach Ajax Request nachladen | Tobias Seckinger

    [...] Twitter noch im Internet gibts dazu wirklich viel Infos. Ein guter Ansatz findet sich beispielweise hier. Leider funktionierte das in meinem Fall nicht. Ich bekam eine wenig aussagekräftige Fehlermeldung [...]

  • Kevmc

    Since you’re using jQuery you can use the getScript() function to reload/rerun the twitter widget script once you have added the new content to the page.

    // make a jQuery reference to your freshly rendered content
    var newContent=$(‘selector for wherever your ajax content has been rendered’);

    // does it contain any tweet links?
    if($(‘a.twitter-share-button’, newContent).length > 0){
        // re-load the widgets script, it is probably cached anyway so there’s no download overhead, but this makes it run again.
        $.getScript(‘http://platform.twitter.com/widgets.js‘);                           
    }       

  • http://www.facebook.com/sahaskatta Sahas Katta

    Same problem here! Just started happening. Please let me know if you find a solution!

  • Ritch

    This seems to fix it for me… cheers!

    This request might be slightly more efficient though… 
    $.ajax({ url: ‘http://platform.twitter.com/widgets.js', dataType: ‘script’, cache:true});
    With the cache flag set to true it does not even seem to poll twitters server again for the script – it just pulls it from the browsers cache.

  • David

    Thanks Ritch for the idea.
    That helped me a lot :)

     Cheers!

  • http://twitter.com/pauldwaite Paul D. Waite

    Looks like using twttr.TweetButton in this way wasn’t supported, and doesn’t work in the latest API update:

    http://groups.google.com/group/twitter-development-talk/browse_thread/thread/bcda486acdf4ab42/6a557050f850ccf2?lnk=gst&q=+twttr.TweetButton#6a557050f850ccf2

    You’ll need to dynamically create an iframe-based Tweet button instead:

    http://dev.twitter.com/pages/tweet_button#using-an-iframe

  • Smorto

    Thanks so much. This helped me out a ton.

  • Smorto

    Thanks for sharing!

  • http://www.comparemyfare.com developer

    I am having a width problem are these morroe than 160px when you put FB and Twitter together?

  • http://www.comparemyfare.com developer

    I am having a width problem are these morroe than 160px when you put FB and Twitter together?

  • http://recovery-review.com decil

    Not exactly correct.

    Now you can initialize new buttons simply calling twttr.widgets.load();

  • Digitalpbk

    I am getting this error
    twttr.TweetButton is not a constructor

  • http://twitter.com/TomasNeme Tomas Neme

    I’m having trouble with the FB button, I set as an URL http://beta.radiopirate.com/radios/always-salsa/ and it seems that everything is OK with that, but only beta.radiopirate.com gets shared

  • http://froddd.co.uk froddd

    Thanks decil, this call does work indeed, and is much easier to run as you don’t really need to select the button itself — giving it the container as a param is sufficient.

  • http://www.waterproof-camera.us/ waterproof digital camera

    i like the tutorial, you have written very clearly , thanks for the post

  • Jordan

    Yeah they changed some stuff (for the better!) Basically, just call this after your html has loaded;
    twttr.widgets.load()
    Reference – https://dev.twitter.com/discussions/890

  • http://ikeif.net keif

    http://stackoverflow.com/questions/6206471/re-render-tweet-button-via-js
    (from the link:)
    Looks like the twttr.TweetButton constructor was never supported, and now no longer works after the last API update:http://groups.google.com/group/twitter-development-talk/browse_thread/thread/bcda486acdf4ab42/6a557050f850ccf2?lnk=gst&q=+twttr.TweetButton#6a557050f850ccf2The supported method is to create an iframe-based Tweet button dynamically:http://dev.twitter.com/pages/tweet_button#using-an-iframe

  • http://twitter.com/sharmarajukumar raju kumar sharma

    how to dynemic create twitter on tweet

  • http://www.smallnotez.com/ Ifat

    thanks for the tutorial :)

  • http://twitter.com/ingpazzo Gaetano D’Onghia

     This appears to be the only method…
    $.ajax({ url: ‘http://platform.twitter.com/widgets.js', dataType: ‘script’, cache:true});

  • http://twitter.com/AnthonyVader Anthony Vader

    Does anyone know how to do the same thing with a Digg button?

  • http://twitter.com/AnthonyVader Anthony Vader

    In answer to my own question, I got dynamic Digg Smart buttons working by doing this:

      var encodedURL = encodeURI(url); 
    var diggHTML = ‘<a class=”DiggThisButton DiggCompact” href=”http://digg.com/submit?url=’ + encodedURL + ‘”></a>’; 
    $(“#someDiv”).append(diggHTML); 
    $.ajax({ url: ‘http://widgets.digg.com/buttons.js', dataType: ‘script’, cache:true, async:false});

  • Ezekiel

    Thank you for this! Helped me a lot!

  • AlphaLemon CMS

    Hi,

    the constructor

    var tweet_button = new twttr.TweetButton( $( this ).get( 0 ) );

    no longer exists. To have the twitter buttons rendered simply call:

    twttr.widgets.load();

blog comments powered by Disqus