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!