Monday, May 02, 2011

Twitter share button with changeable url and no external widgets.js

Yesterday I wanted to add a "share on Twitter" button to the Combo.fm homepage, so users can share their created combo stations via Twitter, The normal button available by Twitter did not work as I wanted it to, it initializes the Button on page load. If you want to change the url afterwards, nothing happens and even the iframe solution did not work. Shame on you, Twitter!

So I created a custom solution which basically can do the same, but without the counter. Best thing is, it does not depend on the widgets.js so the page doesn't take ages to load.

I basically used the link solution for the tweet button. So assume we want to share an url mydynamicurl.com/mysubpage, but use example.com as the count url(in case twitter or I get this fixed).
The example.com/mydynamicsubpageurl is created within the website dynamically, depending on the users input and you are in no way able to put it as your current url.

Put the following code somewhere in your section:

<script type="text/javascript">
function shareOnTwitter(url) {
popupWindow = window.open(url,'popUpWindow','height=300,width=500,resizable=yes,scrollbars=yes,toolbar=yes,menubar=no,location=no,directories=no,status=yes');
</script>

This function is responsible for creating a popup window where you can tweet the shared url.

For the share button use the following:

<a id="shareOnTwitter" title="Tweet example.com!" href="http://twitter.com/share?url=%%shareUrl%%&counturl=http://example.com&text=Check%20outthis%20awesome%20dynamic%20page&via=mytwitteruser" onclick="shareOnTwitter(this.href);return false;"><img alt="Tweet this!" src="http://twitter-badges.s3.amazonaws.com/t_small-a.png"></a>

The parameters are explained in the tweet button documentation linked above. If the user clicks the link, the shareOnTwitter function will be called with the link's href attribute, which will open a nice popup window that uses Twitters intent page for tweeting.
See that I use a placeholder %%shareUrl%% in the url. We will use jQuery and the JavaScript replace function to insert the actual url:
function setTwitterShareUrl(url) {
$('#shareOnTwitter').attr('href', $('#shareOnTwitter').attr('href').replace(/%%shareUrl%%/,url));
}


If you want to change the url more than one time, you might want to use the link in a template element and call the replace() function simply on the html. Then replace the old share link attribute with the new one.