jQuery code / syntax guidelines

We all write our own jQuery code and since creating custom jQuery plugins is so easy, we all create our own jQuery plugins. And all of us have our own code syntax preferences. For example:

function myFunction() {
    ...
}

// some prefere it like this
function myFunction()
{
    ...
}

If you want to publish your jQuery plugins following jQuery core code writing guidelines is a good idea. This would make your code more easier to read to other jQuery developers. Follow the link above and go through the guidelines (it will only take a few minutes). The guidelines page shows gives you general guidelines, but I went through the jQuery core code and found several additional ones. I lay they out at the end of this post.

In short, the official guidelines are as follows: (Taken from official docs)

  1. Use tabs to indent your code
  2. Use liberal spacing":
    function myFunction ( myVar, myVar2 ) {
        // Pay attention to spaces around
        // the brackets and curly brackets
    }
  3. Use strict equality checks whenever possible (===)
  4. Braces should always be used on blocks and statements should not be on the same line as a conditionals:
    // NO:
    if ( true ) blah();
    
    // YES:
    if ( true ) {
       blah();
    }
  5. When checking an object type:
    String: typeof object === "string"
    Number: typeof object === "number"
    Function: jQuery.isFunction(object)
    Array: jQuery.isArray(object)
    Element: object.nodeType
    
    See full list on official docs page (link above)
  6. Don't use "string".match() for RegExp, instead use .test() or .exec()
  7. Node related rules:
    • .nodeName should always be used in favor of .tagName.
    • .nodeType should be used to determine the classification of a node (not .nodeName).
    • Only attach data using .data().

Now let’s see other additional rules that I could spot reading the jQuery core code.

Additional jQuery code / syntax guidelines:

  1. The first thing that I noticed was multiline comments did not use common /* comment */ syntax. In jQuery core all multiline comments use line comment syntax // comment.
    // This is an example of multiline
    // comment syntax used in jQuery core.
  2. Local variables are declared and initialized on one line just below the function declaration with no extra line:
    function someFunction () {
        var target = arguments[0] || {}, i = 1, name;
    
        // Empty line and then the rest of the code
    }
  3. When declaring objects, there is no space between property name and colon:
    {
        myName: "",
        myFunc: function( ) {}
    }
  4. All strings are in double quotes " ", not single quotes ' ':
    var myMarkup = "<a href='/a'>a</a>";
  5. The last but not least, variable naming uses camelCase.

Dynamically create iframe with jQuery

This article explains and shows how to dynamically create an iframe in your HTML document’s DOM using jQuery and/or JavaScript. It also gives you an example code. This post is not extensive explanation of how to manage and work with iframes using jQuery. This post simply shows you how to dynamically create iframes using jQuery and JavaScript and serves as a note.

Creating iframe is similar to creating any DOM element. All you need to do is to use jQuery factory like this:

// Create an iframe element
$(‘<iframe />’);

// You can also create it with attributes set
$('<iframe id="myFrame" name="myFrame">');

// Finnaly attach it into the DOM
$('<iframe id="myFrame" name="myFrame">').appendTo('body');

Don’t forget that the iframe source is just an iframe’s attribute. So you can set that just like any other attribute.

// Setting iframe's source
$('<iframe />').attr('src', 'http://www.google.com'); 

UPDATE:

As BinaryKitten point’s out below, with jQuery 1.4 you can do it using the following syntax:

// Set attributes as a second parameter
$('<iframe />', {
    name: 'myFrame',
    id:   'myFrame',
    ...
}).appendTo('body');

Cross-domain RSS to JSON converter [jQuery plugin]

No doubt that Web2.0 is one of the best things that happened in our lifetime (besides the internet itself). When we mention Web2.0 first things that come into our minds are AJAX, rounded corners, clean and light layouts and of course RSS feeds. Nowadays, you either provide an RSS feed or consume it in your web app using AJAX/JavaScript.

The only bad thing is that you can not request cross-site content with AJAX requests. Requesting someone else’s RSS in your JavaScript falls into this limitations. One way to overcome this problem is to apply a server-side proxy workaround. However, there is even better solution and workaround – RSS to JSON conversion.

Basically, using Google Feeds API service and jQuery plugin you can request and get any RSS from different domain converted into the JSON object in your javascript.

Let’s see an example of RSS2JSON converter:

<script src="jquery.js"></script>
<script src="jquery.jgfeed.js"></script>
<script>
$.jGFeed('http://twitter.com/statuses/user_timeline/26767000.rss',
  function(feeds){
    // Check for errors
    if(!feeds){
      // there was an error
      return false;
    }
    // do whatever you want with feeds here
    for(var i=0; i<feeds.entries.length; i++){
      var entry = feeds.entries[i];
      // Entry title
      entry.title;
    }
  }, 10);
</script>

In order to have universal client-side RSS to JSON converter you first need to include jquery.js and Google Feeds API plugin jquery.jgfeed.js. Then use jQuery plugin and Google Feeds API to get reliable and fast RSS to JSON(P) converter.

The code above gets Twitter RSS feeds in JSON format and does whatever it wants with it. Great workaround isn’t it :)

To see jGFeed()’s argument lists and how to use it please read this post.

Create callback functions for your jQuery plugins & extensions

Most of the time custom jQuery plugins and extensions that we create do not use a callback functions. They usually simply work on DOM elements or do some calculations. But there are cases when we need to define our own custom callback functions for our plugins. And this is especially true when our plugins utilize AJAX querying.

Let’s say our custom jQuery extension gets data by making some AJAX request.

$.extend({
  myFunc : function(someArg){
    var url = "http://site.com?q=" + someArg;
    $.getJSON(url, function(data){

        // our function definition hardcoded

    });
  }
});

What is bad in this jQuery code is that the callback function is defined and hardcoded right in the plugin itself. The plugin is not really flexible and its user will have to change the plugin code, which is bad!

So the solution is to define your own custom callback function argument. Here is how it is done:

$.extend({
  myFunc : function(someArg, callbackFnk){
    var url = "http://site.com?q=" + someArg;
    $.getJSON(url, function(data){

      // now we are calling our own callback function
      if(typeof callbackFnk == 'function'){
        callbackFnk.call(this, data);
      }

    });
  }
});

$.myFunc(args, function(){
  // now my function is not hardcoded
  // in the plugin itself
});

The above code shows you how to create a callback function for AJAX load, but if you want to create a simple callback function for your jQuery plugin, for example the one that executes on your own custom events. To achive this you can do the following:

$.extend({
  myFunc : function(someArg, callbackFnk){
    // do something here
    var data = 'test';
 
    // now call a callback function
    if(typeof callbackFnk == 'function'){
      callbackFnk.call(this, data);
    }
  }
});

$.myFunc(someArg, function(arg){
  // now my function is not hardcoded
  // in the plugin itself
  // and arg = 'test'
});

jQuery Twitter plugin update – jTwitter 1.1

Some time ago I created jQuery Twitter plugin – jTwitter. Plugin lets you get data about any Twitter user, such as user’s bio, profile image, homepage URL, background image URL, following count, followers count, messages count, etc. without any Twitter API key. It is very useful to attach additional Twitter data to your site’s user profiles, etc.

However, it was not very handy for creating your own and custom Twitter Badge. Well, right until now! I updated jTwitter plugin and now it can get you not only Twitter user details but also any number of that user’s latest posts. And yes, all these you can do without any Twitter API keys.

Here is the main function and its argument details:

$.jTwitter(username, numberOfPosts, callbackFunction);

/* username - Twitter username
   numberOfPosts - Number of user posts to get
   callbackFunction - callback function to call
   when data is loaded */

Let’s see a real life example now. In example below, we are fetching latest 3 posts of jQueryHowto Twitter user and appending those post messages to some DOM element with an id=tweets.

$.jTwitter('jQueryHowto', 3, function(posts){
  for(var i=0; i<posts.length; i++){
     $('#tweets').append(posts[i].text);
  }
});
You can see example usage and demo here.

To get a clear view of what data is returned and available in your callback function here is an example of returned JSON data object:

/*
    Example of returned object
*/

[
  {
    'in_reply_to_user_id':null,
    'in_reply_to_screen_name':null,
    'source':'web',
    'created_at':'Fri Sep 18 06:11:15 +0000 2009',
    'truncated':false,
    'user':{
      'profile_background_color':'9ae4e8',
      'description':'jQuery and JavaScript howtos, tutorials, hacks, tips and performanace tests. Ask your jQuery questions here...',
      'notifications':false,
      'time_zone':'Central Time (US & Canada)',
      'url':'http://jquery-howto.blogspot.com',
      'screen_name':'jQueryHowto',
      'following':true,
      'profile_sidebar_fill_color':'e0ff92',
      'created_at':'Thu Mar 26 14:58:19 +0000 2009',
      'profile_sidebar_border_color':'87bc44',
      'followers_count':2042,
      'statuses_count':505,
      'friends_count':1015,
      'profile_text_color':'000000',
      'protected':false,
      'profile_background_image_url':'http://s.twimg.com/a/1253209888/images/themes/theme1/bg.png',
      'location':'',
      'name':'jQuery HowTo',
      'favourites_count':15,
      'profile_link_color':'0000ff',
      'id':26767000,
      'verified':false,
      'profile_background_tile':false,
      'utc_offset':-21600,
      'profile_image_url':'http://a3.twimg.com/profile_images/110763033/jquery_normal.gif'
      },
    'in_reply_to_status_id':null,
    'id':4073301536,
    'favorited':false,
    'text':'Host jQuery on Microsoft CDN servers http://retwt.me/2N3P'
  },
  {
    'in_reply_to_user_id':null,
    'in_reply_to_screen_name':null,
    'source':'<a href="http://www.hootsuite.com" rel="nofollow">HootSuite</a>',
    'created_at':'Thu Sep 17 17:20:21 +0000 2009',
    'truncated':false,
    'user':{
      'profile_sidebar_fill_color':'e0ff92',
      'description':'jQuery and JavaScript howtos, tutorials, hacks, tips and performanace tests. Ask your jQuery questions here...',
      'friends_count':1015,
      'url':'http://jquery-howto.blogspot.com',
      'screen_name':'jQueryHowto',
      'following':false,
      'profile_sidebar_border_color':'87bc44',
      'favourites_count':15,
      'created_at':'Thu Mar 26 14:58:19 +0000 2009',
      'profile_text_color':'000000',
      'profile_background_image_url':'http://s.twimg.com/a/1253141863/images/themes/theme1/bg.png',
      'profile_link_color':'0000ff',
      'protected':false,
      'verified':false,
      'statuses_count':504,
      'profile_background_tile':false,
      'location':'',
      'name':'jQuery HowTo',
      'profile_background_color':'9ae4e8',
      'id':26767000,
      'notifications':false,
      'time_zone':'Central Time (US & Canada)',
      'utc_offset':-21600,
      'followers_count':2038,
      'profile_image_url':'http://a3.twimg.com/profile_images/110763033/jquery_normal.gif'
    },
    'in_reply_to_status_id':null,
    'id':4058535256,
    'favorited':false,
    'text':'jQuery Tip: Don't forget that you can load jQuery UI files from Google servers as well http://bit.ly/fJs2r'
  },
  {
    'in_reply_to_user_id':null,
    'in_reply_to_screen_name':null,
    'source':'web',
    'created_at':'Thu Sep 17 05:44:30 +0000 2009',
    'truncated':false,
    'user':{
      'profile_sidebar_fill_color':'e0ff92',
      'description':'jQuery and JavaScript howtos, tutorials, hacks, tips and performanace tests. Ask your jQuery questions here...',
      'friends_count':1015,
      'url':'http://jquery-howto.blogspot.com',
      'screen_name':'jQueryHowto',
      'following':true,
      'profile_sidebar_border_color':'87bc44',
      'favourites_count':15,
      'created_at':'Thu Mar 26 14:58:19 +0000 2009',
      'profile_text_color':'000000',
      'profile_background_image_url':'http://s.twimg.com/a/1253048135/images/themes/theme1/bg.png',
      'profile_link_color':'0000ff','protected':false,
      'verified':false,
      'statuses_count':503,
      'profile_background_tile':false,
      'location':'',
      'name':'jQuery HowTo',
      'profile_background_color':'9ae4e8',
      'id':26767000,
      'notifications':false,
      'time_zone':'Central Time (US & Canada)',
      'utc_offset':-21600,
      'followers_count':2035,
      'profile_image_url':'http://a3.twimg.com/profile_images/110763033/jquery_normal.gif'
    },
    'in_reply_to_status_id':null,
    'id':4048429737,
    'favorited':false,
    'text':'Added a demo page for my 'How to bind events to AJAX loaded elements' blog post as requested by users http://bit.ly/q2tWe'
  }
]

As you can see, you get not only user’s latest posts but also all the information about posts and user who posted it on Twitter.

You might also be interested in my jQuery YouTube Plugin.
It gets any YouTube video’s thumbnail image.

If you are using Twitter don’t forget to follow me.