Changing your Twitter status with jQuery

Twitter allows its users to dynamically modify their online status by using the special URL, where the encoded-string URL parameter is simply the text string you want to be displayed in your Twitter status box before tweeting it by clicking on "Tweet". This string must be encoded using the JavaScript's core global function encodeURIComponent(), which converts all special characters in an URL-friendly encoded string. So why don't we use jQuery to automate this process? Here's a simple plugin:

(function($) {

  $.fn.twitterStatus = function(URLString) {
    if(this[0].tagName.toLowerCase() !== 'a') {
      throw new Error('twitterStatus works only on a elements');
    URLString = URLString || this.text();
    var encodedString = window.encodeURIComponent(URLString);
    var baseURL = '';
    var href = baseURL + encodedString;
    this.attr('href', href);
    return this;


The twitterStatus() plugin works only with links, so the first thing we need to do is to check whether the current element is a link or not. If not, we return a JavaScript error and exit from the function. Then we encode the URLString parameter passed to our function using the JavaScript's global function encodeURIComponent() and we merge this parameter with the Twitter's base URL. Finally, we set the href attribute to the newly created string.

A simple test:

$(document).ready(function() {

  $('#twtr').twitterStatus('Testing the twitterStatus jQuery plugin');



Live test

Leave a Reply

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