tomasdev

web development handcrafted

Update Tweet button on AJAX

25 Oct, 2011. Written by Tom Roggero

So... If you need to show for example, a Twitter sharing button in an overlay, and it's contents come from an AJAX (asynchronous) request, you might need to parse things again. And of course, you don't want to include widgets.js as many times as you have a new button. There used to be a hack which was:

 
new twttr.TweetButton(element).render();
 

We're not happy now, that function doesn't work anymore. The correct new method to use is:

 
twttr.widgets.load();
 

Check the Twitter API for more options, I will just show a button dynamically added that shares the page it's currently on. You can add that call in the callback function or after appending the button such as (example using jQuery):

 
// button markup
var content = '<a href="https://twitter.com/share" class="twitter-share-button" data-count="none">Tweet</a>';
$('#container').html(content);
// now refresh the widgets!
twttr.widgets.load();
 

Of course we're guessing you have already included widgets.js in your page.

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

Same methodology applies to Facebook Sharing button which markup is:

 
<a name="fb_share" type="button" share_url="http://tomasdev.com.ar">Share</a>
 

You can refresh or parse again the button using:

 
FB.Share.renderAll();
 

It's quite useful when working with dynamic URLs or asynchronous content loading.

Comments /

Leave a Reply