jQuery: create a Twitter tweet button

Twitter provides a useful guide to create and customize our tweet buttons. In this post, I'll show you how to implement a basic Twitter tweet button with jQuery. Let's get to work.

Twitter allows us to share links and web pages through a query URL embedded within each tweet link. This URL is made up of several parts. The most relevant are:

  1. Base URL: http://twitter.com/share?
  2. url: The URL of the web page to share.
  3. via: The Twitter username of the author of the page (if any).
  4. text: The textual content of the title (defaults to the page's title).

Let's build a simple jQuery plugin that creates a tweet button:

(function($) {

  $.fn.tweetButton = function(options) {
  
    var that = this;
    var settings = {
    
      url: location.href,
      via: 'gabromanato',
      text: document.title,
      linkText: 'Tweet',
      linkClass: 'twitter'
      
      
    
    };
    
    options = $.extend(settings, options);
    
    return that.each(function() {
    
      var html = '<a class="' + options.linkClass + '"';
      html += ' href="http://twitter.com/share?' + 'url=' +
              encodeURIComponent(options.url) + '&via=' +
              options.via + '&text=' + options.text + '">' + options.linkText + '</a>';
              
      that.html(html);
    
    
    });
  
  
  };

})(jQuery);

Basic usage:

$(function() {

  $('#test').tweetButton();

});

Because of its simplicity, this plugin doesn't return the number of tweets already shared. Anyway, you can take care of this by counting of many times the button has been clicked. You can see the demo below.

Demo

Live demo

Leave a Reply

Note: Only a member of this blog may post a comment.