Dynamic Twitter and Facebook social buttons

On my Azure Rocks! site, I display YouTube videos dynamically in an iFrame.  I was looking to add social buttons so viewers can tweet about it or share/like on Facebook.  Adding social buttons is easy but they are designed to be placed on a page, not being added dynamically.  I figured out that you just can't change their properties like the URL with JQuery.  Stuck?  Nope.  A quick search revealed that the easiest way to deal with this problem is to simply destroy the previous instance and inject a new button with the new properties.

Simply place a couple of divs to act as placeholders:

<div id="twitterShare"></div>
<div id="facebookShare"></div>

Next, inject the buttons.  For Facebook, I used the iFrame method:

$("#facebookShare").html(' ');
$("#facebookShare").html('<iframe src="//www.facebook.com/plugins/like.php?href=' + 'http://www.azurerocks.com/' + videoId + '&width&layout=button&action=like&show_faces=false&share=true&height=35&appId=yourAppId"  scrolling="no" frameborder="0" style="border:none; overflow:hidden; height:35px;" allowtransparency="true"></iframe>');

For Twitter, I used the share link method:

$("#twitterShare").html(' ');
$("#twitterShare").html('<a href="https://twitter.com/share" class="twitter-share-button" data-url="' + share_url + '" data-text="' + title + '" data-count="none" data-via="WinAzureRocks" data-count="none" data-hashtags="WindowsAzure">Tweet</a>');

Note that you must call the widgets load method to load the button correctly.

Nice but I faced I issue with the Twitter button.  The load method worked perfectly once the page has been fully loaded but I can load the page and show a video directly by having a YouTube video ID as an optional parameter (www.azurerocks.com/youtubeid).  The problem is that I was calling the load method too soon, I guess before the Twitter js has been fully loaded.  Anyways, the way to deal with that is to force load the library:

$.getScript('//platform.twitter.com/widgets.js', function(){

 Now both buttons works perfectly.

blog comments powered by Disqus

Page List

Month List