Elegant Twitter share button and dialog with jQuery

Twitter, Facebook and many other social networking website offers embedded code to add share buttons on our website. The thing is, they all have different dimensions and looks, which can make your page style quite inconsistent. So the idea is to use a custom image for our share button, and then a bit of javascript to create our dialog window with the social website.

Firstly, we create the html for the link:

<a class="tweet" title="Expert in Web Design and Online Software Development @guillaumepiot" href="http://gpiot.com" target="_blank">Tweet this!</a>

We use the href attribute to define the URL to share and the title attribute to enter a custom share message. Please note that the "&" must be avoided as it will break the share url.

We then use jQuery for all the action:

  • Binding a new event to the link
  • Parsing the link attribute
  • Opening a popup window with the Twitter page dialog
// We bind a new event to our link
$('a.tweet').click(function(e){
  //We tell our browser not to follow that link
  e.preventDefault();
  //We get the URL of the link
  var loc = $(this).attr('href');
  //We get the title of the link
  var title  = escape($(this).attr('title'));
  //We trigger a new window with the Twitter dialog, in the middle of the page
  window.open('http://twitter.com/share?url=' + loc + '&text=' + title + '&', 'twitterwindow', 'height=450, width=550, top='+($(window).height()/2 - 225) +', left='+$(window).width()/2 +', toolbar=0, location=0, menubar=0, directories=0, scrollbars=0');
});

View Gist

Demo

View the online demo and download the source code

< / >