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.

JavaScript / jQuery password generator

This month, October, is a National Cyber Security Awareness Month. The aim is to increase cyber and internet security awareness among surfers. Google and others are joining the move. So I thought I would write a post regarding internet security to add my 2 cents. In this post you will find JavaScript function that generates random passwords of any length as well as jQuery version.

JavaScript Password Generator

function password(length, special) {
  var iteration = 0;
  var password = "";
  var randomNumber;
  if(special == undefined){
      var special = false;
  }
  while(iteration < length){
    randomNumber = (Math.floor((Math.random() * 100)) % 94) + 33;
    if(!special){
      if ((randomNumber >=33) && (randomNumber <=47)) { continue; }
      if ((randomNumber >=58) && (randomNumber <=64)) { continue; }
      if ((randomNumber >=91) && (randomNumber <=96)) { continue; }
      if ((randomNumber >=123) && (randomNumber <=126)) { continue; }
    }
    iteration++;
    password += String.fromCharCode(randomNumber);
  }
  return password;
}

This function takes two parameters: integer value for password length and optional boolean value true if you want to include special characters in your generated passwords.

Examples of generated passwords

password(8);
// Outputs: Yrc7TxX3

password(12, true);
//Outputs: C}4_ege!P&#M

jQuery password generator

$.extend({ 
  password: function (length, special) {
    var iteration = 0;
    var password = "";
    var randomNumber;
    if(special == undefined){
        var special = false;
    }
    while(iteration < length){
        randomNumber = (Math.floor((Math.random() * 100)) % 94) + 33;
        if(!special){
            if ((randomNumber >=33) && (randomNumber <=47)) { continue; }
            if ((randomNumber >=58) && (randomNumber <=64)) { continue; }
            if ((randomNumber >=91) && (randomNumber <=96)) { continue; }
            if ((randomNumber >=123) && (randomNumber <=126)) { continue; }
        }
        iteration++;
        password += String.fromCharCode(randomNumber);
    }
    return password;
  }
});

// How to use
$.password(8);
$.password(12, true);

Host jQuery on Microsoft CDN servers

After Microsoft decided to ship and use jQuery library for its JavaScript needs in Visual Studio, hosting jQuery on Microsoft CDN servers is actually a logical and good decision. Yes, some of us might argue that Google already hosts jQuery, but Microsoft can not recommend to use its competitor’s services, can it?! :)

Anyway, intention of this post is not to discuss why Microsoft introduced its own jQuery hosted servers, bu to share links to Microsoft hosted jQuery library. Here we go:

jQuery 1.4.x
http://ajax.microsoft.com/ajax/jQuery/jquery-1.4.2.js
http://ajax.microsoft.com/ajax/jQuery/jquery-1.4.2.min.js
http://ajax.microsoft.com/ajax/jQuery/jquery-1.4.1-vsdoc.js

jQuery 1.3.2
http://ajax.Microsoft.com/ajax/jQuery/jquery-1.3.2.js
http://ajax.Microsoft.com/ajax/jQuery/jquery-1.3.2.min.js
http://ajax.Microsoft.com/ajax/jQuery/jquery-1.3.2-vsdoc.js
http://ajax.Microsoft.com/ajax/jQuery/jquery-1.3.2.min-vsdoc.js

Microsoft also host jQuery Validation and jQuery UI files.

Currently Microsoft AJAX CDN hosts only jQuery version 1.3.2, but they will add more releases in the future. To see a full list of the JavaScript libraries and their URLs that are already hosted on CDN cache go here: www.asp.net/ajax/cdn

Get URL parameters & values with jQuery

In this post, I would like to share a little jQuery code snippet that makes getting URL parameters and their values more convenient.

Recently, while working on one of my projects, I needed to read and get parameter values from URL string of the current page that was constructed and sent by PHP script. I came across this short and sweet JavaScript code snippet by Roshambo that does just that.

// Read a page's GET URL variables and return them as an associative array.
function getUrlVars()
{
    var vars = [], hash;
    var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
    for(var i = 0; i < hashes.length; i++)
    {
        hash = hashes[i].split('=');
        vars.push(hash[0]);
        vars[hash[0]] = hash[1];
    }
    return vars;
}

The function returns an array/object with your URL parameters and their values. For example, consider we have the following URL:

http://www.example.com/?me=myValue&name2=SomeOtherValue

Calling getUrlVars() function would return you the following array:

{
    "me"    : "myValue",
    "name2" : "SomeOtherValue"
}

To get a value of first parameter you would do this:

var first = getUrlVars()["me"];

// To get the second parameter
var second = getUrlVars()["name2"];

To make the script syntax to look more jQuery like syntax I rewrote it as an extension for jQuery:

$.extend({
  getUrlVars: function(){
    var vars = [], hash;
    var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
    for(var i = 0; i < hashes.length; i++)
    {
      hash = hashes[i].split('=');
      vars.push(hash[0]);
      vars[hash[0]] = hash[1];
    }
    return vars;
  },
  getUrlVar: function(name){
    return $.getUrlVars()[name];
  }
});

Now, if you include the above code in your javascript file, you can get URL parameter values in the following way:

// Get object of URL parameters
var allVars = $.getUrlVars();

// Getting URL var by its nam
var byName = $.getUrlVar('name');

That’s it! You might also find the following jQuery related articles on this blogs interesting:

  1. Cross-domain AJAX querying with jQuery
  2. Javascript for() loop vs jQuery .each() performance comparison
  3. Create jQuery custom selectors with parameters
  4. JavaScript / jQuery password generator

QR Code (generator) plugin for jQuery & JavaScript

I recently came across a 2 dimensional barcode called QR Code. QR code’s are popular in Japan and they are mainly used there to quickly get to some website on their mobiles by simply taking a picture of the QR code. You may read more about QR codes on Wikipedia.

Here is an example of QR code for jQuery HowTo blog:

qrcode-jquery-howto

If you have a QR code reader on your mobile take a picture of it and it will open this website. Cool ha?!

Anyway, there are plenty of free online QR code generator sites, but no JavaScript and jQuery plugins/functions. So, I quickly searched for a free online QR code generator sites with “friendly” URL’s and put together a javascript and jQuery functions that generate QR barcode image’s URL for passed URLs. I used Kaywa & University of Bath services.

See jQuery and QR code in action on this demo page.

Here are javascript and jQuery QR code functions:

// JavaScript function
function qrcode(url, size){
  if(typeof(size) == 'undefined') size = 8;
  return 'http://qrcode.kaywa.com/img.php?s='+size+'&d='+url;
}
qrcode('http://jquery-howto.blogspot.com');

// jQuery plugin
(function ($) { 
  $.fn.qrcode = function(url, size) { 
    if(typeof(size) == 'undefined') size = 8;
    return 'http://qrcode.kaywa.com/img.php?s='+size+'&d='+url;
  }
})(jQuery);
$().qrcode('http://www.google.com');

The code above utilizes Kaywa’s online QR code generator. You can specify image site as the second argument to the function. The size argument mut be between 1 and 40 and the generated image will 32 x your argument.

Here is javascript and jQuery code for University of Bath barcode generator:

// JavaScript function
function qrcode(url){
  return 'http://go.bath.ac.uk/qr/download?DATA='+url;
}
qrcode('http://jquery-howto.blogspot.com');

// jQuery plugin
(function ($) { 
  $.fn.qrcode = function(url) { 
    return 'http://go.bath.ac.uk/qr/download?DATA='+url;
  }
})(jQuery);
$().qrcode('http://www.google.com');

NOTE: You can encode plain text messages. They are not limited to URLs...

Can't set / change CSS background image with jQuery problem solution

Hello everyone. I’ve been busy lately with some projects and could not write much on “jQuery HowTo” blog. So, when I came across this little problem, I thought I would share it with you.

Anyway, I was working on one of my projects and I needed to set a background image using jQuery on some div. At first my background setting code looked like this:

$('#myDiv').css('background-image', 'my_image.jpg');
// OR
$('#myDiv').css('background', 'path/to/image.jpg');

But to my surprise it didn’t do the trick. My div’s had no background images. FireBug showed no CSS background properties set and I could not see why background images were not being set by jQuery. Anyway, after 10-20 minutes I realized that jQuery sets CSS properties as key : value and in our case valued had to be in url(image.jpg) form.

Solution to “background images are not being set” problem is to set them like this:

$('#myDiv').css('background-image', 'url(my_image.jpg)');
// OR
$('#myDiv').css('background', 'url(path/to/image.jpg)');

jQuery.noConflict – Resolving conflicts with other javascript libraries that use $() function

One of the reasons that make a software popular is its extensions and plugins. jQuery has plenty of plugins that do almost anything you want, from simple button hide to full blown galleries. Plugins let non developers easily add functionality they need to their websites and there are times when one might include more than one javascript library such as prototype.js, YUI or mootools with jQuery. They all use $ as their main function name. Including second library might brake the behavior of the first one. To resolve such cases jQuery introduces .noConflict() method.

When you call .noConflict() jQuery will return $() to it’s previous owner and you will need to use jQuery() instead of shorthand $() function.

.noConflict() usage example (From jQuery Docs site)

<html>
  <head>
  <script src="prototype.js"></script>
  <script src="jquery.js"></script>
  <script>
    jQuery.noConflict();
    // Use jQuery via jQuery(...)
    jQuery(document).ready(function(){
        jQuery("div").hide();
    });
    // Use Prototype with $(...), etc.
    $('someid').hide();
  </script>
  </head>
  <body></body>
</html>

You can also use the following code snippets to still use $() in your code, but with one drawback, you will not have access to your other library’s $() method.

// Method 1
jQuery(document).ready(function($){
    $("div").hide();
});

// Method 2
(function($) {
    /* some code that uses $ */ 
})(jQuery);

TIP:
Don’t forget that you can always assign jQuery to any other variable name to use it as your shorthand: var $_ = jQuery;

Identifying & locating mouse position in jQuery

While writing the next jQuery tutorial I needed to identify and locate where the mouse was on the page. Tracking mouse position on the page with jQuery is easy. You don’t need to check what browser the script is running like it is used to be with plain JavaScript. To identify where the mouse is in jQuery all you have to do is to read event object’s .pageX and .pageY properties.

Example:

$().mousemove(function(e){
   // e.pageX - gives you X position
   // e.pageY - gives you Y position
});

The above jQuery code is binding a new ‘on mouse move’ event to the current document and triggered every time mouse moves. The coordinates are calculated in pixels from top left corner of the document. See the above code in action.

You may also want to know the coordinates of the mouse relative to some <div> or an element. Since jQuery returns mouse position relative to the document root, by subtracting element’s position from document root you get mouse positions relative to that element. Long story short here is the code to do just that:

$("#someDiv").click(function(e){
    var relativeX = e.pageX - this.offsetLeft;
    var relativeY = e.pageY - this.offsetTop;
});

Don’t forget that you can bind any mouse event to any element and then get mouse positions. You can easily create a draggable object with click and mousemove events by simply setting the CSS top and left values to .pageX and .pageY.

Anyway, that’s how you locate and handle mouse positions in jQuery. As always, you don’t need to worry about cross browser compatibility issues while using jQuery. To learn more see more examples here.

jQuery custom selectors with parameters

My last tutorial on how to create a custom jQuery selector showed you the basics of creating custom filters in jQuery. Now, it is time to get more serious with selectors and create more advanced jQuery selectors – custom jQuery selectors with parameters. To get an idea of what I am talking about think of :contains(someText) selector.

Anyway, let’s create our own jQuery selector that takes arguments. The basic syntax is the same:

$.expr[':'].test = function(obj, index, meta, stack){
    /* obj - is a current DOM element
       index - the current loop index in stack
       meta - meta data about your selector !!!
       stack - stack of all elements to loop
   
       Return true to include current element
       Return false to explude current element
    */
};

meta is a parameter we are interested in. meta is an array that carries an information about our selector. Here is what it looks like:

$('a:test(argument)');
//meta would carry the following info:
[
    ':test(argument)', // full selector
    'test',            // only selector
    '',                // quotes used
    'argument'         // parameters
]

$('a:test("arg1, arg2")');
//meta would carry the following info:
[
    ':test('arg1, arg2')', // full selector
    'test',                // only selector
    '"',                   // quotes used
    'arg1, arg2'           // parameters
]

Here as you can see, we can make use of the arrays fourth (meta[3]) value to get a hang of our parameters.

Creating custom jQuery selector with parameters

Now, let’s improve our selector from previous post that selects all links with non empty rel attribute and make it select any element with specified non empty attribute. Here is the code to do just that:

$.expr[':'].withAttr = function(obj, index, meta, stack){
  return ($(obj).attr(meta[3]) != '');
};

See it in action here.

Find & select all external links with jQuery

Selecting all external links and amending them in some way is probably one of the most used jQuery tutorials. By selecting all anchor links on the page and for example adding a CSS class with only one jQuery line shows how jQuery is simple and powerful. Also if you are progressively enhancing your website this is one of the trick you might use.

Actually, I had to select all external links and add an image that indicates it the other day. So, I created a custom jQuery selector called :external that makes finding external links easier for you. (Read “Custom jQuery Selectors” post to learn how to create your own custom selectors)

External links custom jQuery selector code:

// Creating custom :external selector
$.expr[':'].external = function(obj){
    return !obj.href.match(/^mailto\:/)
            && (obj.hostname != location.hostname);
};

// Add 'external' CSS class to all external links
$('a:external').addClass('external');

You can see this code in action here.

You may use the code above to:

  • Add CSS class to all external links
  • Dynamically add an image after the link to indicate that it is an external link
  • Bind a click event to track what links where clicked
  • etc.

Update: The return part was update to take into the account the mailto links as suggested in comments by Phillipp and Karl below.

Custom jQuery selectors

jQuery makes it easy to select elements you need using CSS selectors. It is undoubtedly one of the jQuery features that makes it a great javascript library. On top of standard CSS selectors jQuery introduces some custom selectors that makes your code even more simpler and easier to read.

Examples of custom jQuery selectors are: :header, :even, :odd, :animated, :contains(text), etc.

And the best part is that jQuery lets you create and define your own custom selectors using custom selector creation template below.

jQuery Custom Selector Creation Template:

$.expr[':'].test = function(obj, index, meta, stack){
    // obj - is a current DOM element
    // index - the current loop index in stack
    // meta - meta data about your selector
    // stack - stack of all elements to loop
   
    // Return true to include current element
    // Return false to explude current element
};

// Usage:
$('.someClasses:test').doSomething();

Let’s now create a very simple custom selector using the template above. Let’s say we want a custom jQuery selector that will return elements with nonempty rel attribute.

$.expr[':'].withRel = function(obj){
  var $this = $(obj);
  return ($this.attr('rel') != '');
};

// Usage:
$('a:withRel').css('background-color', 'yellow');

The code above creates a custom selector that will select only elements with not empty rel attributes. Here is the above code’s demo page.

You might also be interested in reading about jQuery custom functions.

UPDATE: Read about creating custom jQuery selectors with parameters.

Mozilla Jetpack & jQuery

Jetpack is a new product of Mozilla Labs. It is basically a new way to create Firefox plugins using web programming languages like HTML, CSS and JavaScript. The idea behind is the same as for Adobe AIR. If you know HTML, CSS and JavaScript you can build a Firefox plugin in no time.

The bad news is that Jetpack is still in early developer testing stage, so it is not available in Firefox yet. The good news is that Jetpack is using jQuery and you can use it to do all kinds of stuff like responding to user click events, manipulate any website DOM elements and use cross-site XMLHttpRequest object, etc. Besides, Jetpack can be setted up to use other javascript libraries such as prototype.js, dojo.js etc. and third party API libraries such as Twitter, Google, etc. API libraries.

Where to go from here?

If you want to learn more about Jetpack and how to use jQuery with it refer to this links:

  1. Watch this Jetpack video
    Good starting point to get an idea of what Jetpack is and how jQuery is used within it. Also good starting point to understand what kind of things can be don with Jetpack.
  2. Read Jetpack tutorial
    Official Jetpack introduction tutorial from Jetpack team. Probably the first article you must read about developing for Jetpack.
  3. Jetpack API documentation
    A list of global variables that are available in your Jetpacks. Currently it has a very limited global variables and functions.
  4. Jetpack plugin for your Firefox
    If you want to develop Jetpacks you need to install this Firefox plugin.
  5. Available Jetpack to investigate the code here and here.
    Most developers prefer understanding the logic and learning by investigating someone else’s code easier.

I am planning to post more Jetpack tutorials on this blog and try to show what kind of things can be done using Jetpack and jQuery. Keep tuned by following me on Twitter (@jQueryHowto) or subscribe to blog’s RSS.

jQuery Beginner tutorials

This post is about a decision I made yesterday to post more jQuery beginner tutorials on the blog.

See a list of all jQuery beginner tutorials on this blog.

There were two reasons for me making this decision:

  1. People are finding this jQuery blog searching for jQuery basics
    Analyzing my Google Analytics account I found that a lot of developers who are landing on this blog through search are jQuery Beginners and looking for basic jQuery method explanations. So publishing more beginner tutorials would benefit them. They would get more relevant information from the new Beginner category posts.
  2. I am being asked more and more jQuery Beginner questions
    I have been quite active on Twitter (@jQueryHowto) and other online discussion boards lately answering and helping developers with their jQuery problems. The jQuery community on twitter is quite active and most of the jQuery problems I came across were jQuery beginners questions. I could not squeeze my ideas or explanations of jQuery basics in 140 characters, so I had to search the web for explanation and post a link to the website.

Message to non beginner readers:

I hope I will not lose intermediate and advanced jQuery developers with this posts. I enjoy your insights and comments on my posts and actually learn a lot more from your feedback. I will try to post no more than one beginner tutorial or insight per my regular post. I hope for your understanding.

List of jQuery Beginner Tutorials and posts:

I actually posted several jQuery Beginner tutorials and method explanations on this blog with backdate. I will try to keep this post updated with the links for my beginner posts so you can bookmark this page or share it with your jQuery beginner colleagues.

See all jQuery beginner tutorials on this blog.
  1. Using $.noConflict()
  2. How to check if checkbox is checked
  3. Identify how many elements were selected
  4. Adding custom functions to jQuery
  5. Identifying & locating mouse position in jQuery
  6. How to load jQuery from Google CDN servers
  7. Setting HTML tag’s attribute in jQuery
  8. Getting HTML tag’s attribute in jQuery
  9. Binding jQuery events to AJAX loaded elements
  10. How to disable and enable an element
  11. Quick tip to solve a problem with setting CSS background image to an element

Javascript for() loop vs jQuery .each() performance comparison

This post is an outcome of 15 minutes of free time and a question that I had yesterday. This question were:

  1. How fast jQuery’s .each() method is?
  2. How does it compare to javascript’s native for loop?

It is clear without any performance tests that native javascript for loop is faster, but I always used jQuery’s .each() utility with caution. It always felt like I will get a performance penalty for using it. So I tried to never use it.

So today, I wrote up a little javascript performance test and got my answers. Basically, I created an array and iterated through it using native for loop and jQuery’s .each() iterator. All I did was just an iteration and no array amendments or any other logic. I know it is very basic, but that’s exactly what I want to know. How fast they iterate!

Performance test code:

console.time('TestNative');
length = myArray.length;
for( i=0; i < length; i++){
  myArray[i];
}
console.timeEnd('TestNative');

console.time('TestjQuery');
jQuery.each(myArray, function(i, val) {
  val;
});
console.timeEnd('TestjQuery');

Performance test results:

JavaScript Native FOR loop

Array size    Time
==========    ======
10,000        7ms
100,000       62ms
1,000,000     613ms


jQuery .each() loop

Array size    Time
==========    ======
10,000        10ms
100,000       177ms
1,000,000     1100ms

As you can see native for loop is never over 1ms. That’s probably because we are not doing anything with our array and browser simply optimizes the code or maybe its that fast :)

Usually we don’t have more than 1000 items in our arrays and objects, that is why I guess it can be concluded that using .each() loop in our code will not cause any performance penalties.

Tip for jQuery & handheld device developers

This week’s usual “Friday short post” about using jQuery in handheld devices. If you are a developer who is using jQuery in applications that were developed for use in environments with small processing power such as handheld devices, mobile phones, PDA’s, etc. you will find this post useful.

Anyway, back to the topic. For whatever reasons you chose to use jQuery in your application (I would suggest using plain javascript for better performance) jQuery effects such as animation, hide and show, etc. most likely were probably one of the reasons. Unfortunately, jQuery effects are process intensive and in “slow” environments it is recommended to turn them off. Fortunately, jQuery provides you with such a method. It lets you disable all animations and effects by changing jQuery.fx.off setting to true.

// Dissable all effects
jQuery.fx.off = true;

// Shorthand
$.fx.off = true;

Now all your effects such as fadeIn(), fadeOut(), slideDown(), slideUp(), etc. will not be animated. They will simply be hidden and shown immediately (by changing CSS rules display:none; display:block;) to save CPU processing time.

NOTE:
By setting the jQuery.fx.off back to false you enable all animations and effects.

Google Feeds API - jQuery plugin

This jQuery plugin utilizes Google’s Feeds API and builds an abstraction layer that makes Google feed API easier to use for jQuery developers. The advantage of using this lightweight jQuery plugin is that you don’t have to learn and go through new API documentation.

Download Google Feed API jQuery plugin – jGFeed.

Here is how to use the plugin:

$.jGFeed('http://feeds.feedburner.com/jQueryHowto',
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);

Available plugin arguments list:

jQuery Google Feed API plugin lets you specify the following settings:

  • url – URL of the feed that you want to load
  • callback – callback function to call after RSS feed is loaded
  • num (optional) – number of blog entries to load (defaults to 3)
  • key (optional) – Google API key to use while loading RSS feeds.

The plugin returns false if there was an error while AJAX loading your feed or the following feed object on success:

{
  "title":"Blog Title",
  "link":"http://www.example.com",
  "author":"Author Name",
  "description":"Blog description.",
  "type":"RSS type (atom10, etc.)",
  "entries":[
    {
      "title":"Blog entry title 1",
      "link":"http://www.example.com/entry-1.html",
      "author":"Post Author Name",
      "publishedDate":"Mon, 25 May 2009 07:07:00 -0700",
      "contentSnippet":"Short blog post snippet ...",
      "content":"Longer snippet of the blog post",
      "categories":[
        "category 1",
        "category 2",
        "category 3"
      ]
    },
    {
      "title":"Blog entry title 2",
      "link":"http://www.example.com/entry-2.html",
      "author":"Post Author Name",
      "publishedDate":"Mon, 25 May 2009 07:07:00 -0700",
      "contentSnippet":"Short blog post snippet ...",
      "content":"Longer snippet of the blog post",
      "categories":[
        "category 3",
        "category 2",
        "category 1"
      ]
    },
    ...
}

If you don’t specify a URL it will also return false. If you want to use your own Google Feed API key you can get one here.

diggthis.js + jQuery .wrap() is not working, causing Firefox to freeze and Safari to crush

I came across a forum post where user was experiencing problems while using Digg this (diggthis.js) button code with jQuery’s .wrap() method. According to him Mozilla Firefox (FF) is freezing and Apple Safari is crushing when he tries to wrap the div that contains diggthis.js file with another new div like so:

<div class="rounded"> 
  <script type="text/javascript"> 
    digg_url = "myURL.com"; 
  </script> 
  <script src="http://digg.com/tools/diggthis.js" type="text/javascript"></script>
</div>

And the jQuery code is:

$(document).ready(function(){ 
    $("div.rounded").wrap('<div></div>'); 
});

This code seems to crush those browsers. Another way to do this is to remove the div that contains the script (.rounded), then create a new <div> and then insert the removed div (.rounded) back into the newly created div like this:

$(document).ready(function(){ 
    $("div.rounded").remove().wrap('<div></div>').appendTo("#somewhere"); 
});

Remove n’th table column - jQuery plugin

My usual short Friday post. Today I would like to share with you a new utility I wrote to work with HTML tables. We already have jQuery functions to add table row, remove table row (on user click), add table row number plugin and now here is jQuery code to remove table column.

jQuery utility to remove table’s n’th column:

$.fn.removeCol = function(col){
    // Make sure col has value
    if(!col){ col = 1; }
    $('tr td:nth-child('+col+'), tr th:nth-child('+col+')', this).remove();
    return this;
};

Just add this code to your javascript file and use it in your jQuery code like this:

// Remove all table's second columns
$('table').removeCol(2);

// Remove table's first column (default)
$('table').removeCol();

The function takes column number to delete as an argument and removes that column. If you don’t supply any column number it removes the first table column by default.

Remove table row on user click

This post is about removing a table row on user click. I needed this functionality for a project of mine. Online application had a table with data that user can dynamically add and remove. With progressive enhancement I also need to add a functionality to one of the tables that enables users to delete table rows when that table row is clicked.

jQuery code to delete clicked table row came out to be surprisingly short, only 3 lines of code.

// Select all table cells to bind a click event
$('table td').click(function(){
    $(this).parent().remove();
});

Here, we are first selecting all table cells to bind our click event. On user click to any table cell click event fires. In the click event we are removing <td>’s parent, which is <tr>, thus removing whole row.

By popular user demand I’m including an example that lets deleting a table row on delete image click. Here is our HTML table:

<table>
  <tr>
    <td>row 1, cell 1</td>
    <td><img class="delete" src="del.gif" /></td>
  </tr>
  <tr>
    <td>row 2, cell 1</td>
    <td><img class="delete" src="del.gif" /></td>
  </tr>
</table>

Here is jQuery code to delete a row on delete image click:

$('table td img.delete').click(function(){
    $(this).parent().parent().remove();
});

See demos here.

Bonus: Also delete a table row from database

The code above is enough if you don’t need to also delete a record from your database table. In my case I had to set up a server side code to do that. With one extra AJAX call to my server side script the functionality was ready.

$('table td').click(function(){
  $.get('deleteRow.php', {id: $(this).parent().attr('id')},
    function(){
        $(this).parent().remove();
  });
});

In the jQuery code above, instead of removing table row straight away we are making an AJAX call to our server side code that also removes that row from our database and then on AJAX call completion we removing table row.

jYouTube - jQuery YouTube Thumbnail plugin. Gets any YouTube video’s image/thumbnail

Writing short scripts and jQuery tips on Fridays became some kind of habit. So this Friday I will give you a small jQuery utility function that will give you a way to get any YouTube video’s still image or in other words any YouTube video’s thumbnail. All you need to know is that YouTube video’s URL address or at least video’s YouTube ID.

Couple of months ago I wrote a javascript function that does just that, gets YouTube video’s thumbnail. Today, I am rewriting that code as a jQuery utility function and releasing it as jQuery plugin called jYouTube.

Download jQuery Youtube plugin - jYouTube

It takes any YouTube video URL or video ID as first parameter and thumbnail size (big or small) as the second parameter. Utility returns that video’s screenshot URL.

Here is how you use jYouTube plugin in your own code:

// Returns big screenshot by video id
$.jYoutube('rSUfWXcNAOw');

// Returns small thumbnail by YouTube video URL
$.jYoutube('http://www.youtube.com/watch?v=rSUfWXcNAOw', 'small');
See the plugin in action on jQuery YouTube demo page.

So here is the final jQuery YouTube plugin code for those who are interested:

$.extend({
  jYoutube: function( url, size ){
    if(url === null){ return ""; }

    size = (size === null) ? "big" : size;
    var vid;
    var results;

    results = url.match("[\\?&]v=([^&#]*)");

    vid = ( results === null ) ? url : results[1];

    if(size == "small"){
      return "http://img.youtube.com/vi/"+vid+"/2.jpg";
    }else {
      return "http://img.youtube.com/vi/"+vid+"/0.jpg";
    }
  }
});
You might also be interested in jQuery Twitter plugin.
Gets any Twitter user information and tweets (does not require API key).

Replacing images at time intervals

This post is somehow a continuation of our previous post on replacing images, but this post is one step closer to creating an image gallery using jQuery. In this post I will show you how to replace one image with another one in specific time intervals. For example: replacing image1.jpg with image2.jpg every 5 seconds.

In javascript, whenever one says “every X seconds” or “time intervals” s/he is talking about javascript’s setInterval() function and this post is no exception.

So, before we continue, we need to define where our images are coming from. Images URLs can be stored in javascript array or we could choose more elegant way and simply read them from HTML document.

Imagine we have this HTML markup:

<div id="myGallery">
  <img src="image1.jpg" class="active" />
  <img src="image2.jpg" />
  <img src="image3.jpg" />
</div>

We need to hide all images but class="active" one and overlay all of them on one another. Here is a CSS to do that:

#myGallery{
  position:relative;
  width:400px; /* Set your image width */
  height:300px; /* Set your image height */
}
#myGallery img{
  display:none;
  position:absolute;
  top:0;
  left:0;
}
#myGallery img.active{
  display:block;
}

Now, lets write jQuery function that will fade out currently active image and fade in the next image. Here is jQuery code:

function swapImages(){
  var $active = $('#myGallery .active');
  var $next = ($('#myGallery .active').next().length > 0) ? $('#myGallery .active').next() : $('#myGallery img:first');
  $active.fadeOut(function(){
    $active.removeClass('active');
    $next.fadeIn().addClass('active');
  });
}

And now all that’s left is to add setInterval() with our function and the time interval we want our image to fade out and fade in.

// Run our swapImages() function every 5secs
setInterval('swapImages()', 5000);

Now we have gallery/slideshow with images changing every 5 seconds. You can easily customize this jQuery script to create your own slideshow.

Here is how your final code should look like:

<html>
<head>
  <script src="jquery.js">
  </script>
  <script>
    function swapImages(){
      var $active = $('#myGallery .active');
      var $next = ($('#myGallery .active').next().length > 0) ? $('#myGallery .active').next() : $('#myGallery img:first');
      $active.fadeOut(function(){
      $active.removeClass('active');
      $next.fadeIn().addClass('active');
      });
    }

    $(document).ready(function(){
      // Run our swapImages() function every 5secs
      setInterval('swapImages()', 5000);
    }
  </script>
  <style>
    #myGallery{
      position:relative;
      width:400px; /* Set your image width */
      height:300px; /* Set your image height */
    }
    #myGallery img{
      display:none;
      position:absolute;
      top:0;
      left:0;
    }
    #myGallery img.active{
      display:block;
    }
  </style>
</head>
<body>
  <div id="myGallery">
    <img src="image1.jpg" class="active" />
    <img src="image2.jpg" />
    <img src="image3.jpg" />
  </div>
</body>
</html>

The code above is simplified.

Disable submit button on form submit

Form submission is one of the most used actions and double form submission is one of most occurred problems in web development. Rather than dealing with this problem server side, eating up your CPU process time, it is much easier and better to deal with this problem client side using JavaScript. When we talk javascript, what it a better way to write it other than using jQuery?!

So this Friday’s quick tip is disabling form submit button on its click or preventing double form submission by disabling submit button.

Consider we have this HTML form in our code:

<form id="myform" action="someUrl.php" method="get">
    <input name="username" />
    <!-- some more form fields -->
    <input id="submit" type="submit" />
</form>

Here is a jQuery code that disables submit button on form submission:

$('#myform').submit(function(){
    $('input[type=submit]', this).attr('disabled', 'disabled');
});

The above jQuery code binds a submit event to our #myform form, then finds its submit button and disables it.

Bonus: disable submit button on form submission for all forms on your page.

// Find ALL <form> tags on your page
$('form').submit(function(){
    // On submit disable its submit button
    $('input[type=submit]', this).attr('disabled', 'disabled');
});
Want to disable any other elements using jQuery? Read my previous “Disabling and enabling elements in jQuery” (very short) post.

Remove the bottom table row using jQuery

I have posted a small jQuery code a while ago which adds a table row at the bottom of any given table. The code takes into the consideration tbody tag and also can be used as a jQuery plugin.

Recently I was asked to write a jQuery or JavaScript code that removes the last/bottom row from the given table. The jQuery code I wrote was surprisingly small.

jQuery code to remove bottom/last table row

// Simple bottom row removal
$('#myTable tr:last').remove();

// Removing n'th (ex. 3rd) row from the table
$('#myTable tr:eq(2)').remove();

Improved jQuery code

We can improve our simple bottom row removal code to take into the consideration the possible <tbody> and <tfoot> HTML tags that can be found in tables.

// Improved code that takes into the consideration
// the <tbody> tag
$('#myTable').each(function(){
    if($('tbody', this).length > 0){
        $('tbody tr:last', this).remove();
    }else {
        $('tr:last', this).remove();
    }
});

// Improved code that for n'th row removal
// In this example we are removing 3rd row
$('#myTable').each(function(){
    if($('tbody', this).length > 0){
        $('tbody tr:eq(2)', this).remove();
    }else {
        $('tr:eq(2)', this).remove();
    }
});

Bonus JavaScript function

You can also turn the code above into the jQuery plugin or JavaScript function. Here is a JavaScript function to remove the bottom table row (you can amend the code to make it remove n’th row).

/*
    Remove the last/bottom table row
*/
function removeTableRow(jQtable){
    jQtable.each(function(){
        if($('tbody', this).length > 0){
            $('tbody tr:last', this).remove();
        }else {
            $('tr:last', this).remove();
        }
    });
}

// Here is how to use it
removeTableRow($('table'));
Also the above javascript function can easily be rewritten as a jQuery plugin. Read this post to learn how to create jQuery plugins.

jQuery Twitter API plugin

UPDATE: Plugin has been updated! For more up to date information read this post.

You might have noticed that I am talking and spending more time on Twitter lately. I have been helping Twitter users with their jQuery related questions and problems as well. If you are using Twitter and have some kind of jQuery related question I will be happy to help.

Anyway, after I found a Twitter JSON(P) API url last week, I spent some time playing with it and ended up with a jQuery plugin that when given a Twitter username retrieves and returns javascript object with user detials such as followers & following counts, full name, homepage URL, etc.

Download jQuery Twitter API - jTwitter here.
Update: Now plugin also get any number of any user's posts.

Here is an example of returned JavaScript object:

// Starting from version 1.1 plugin gets user posts
// the returned object has changed. See update.
{
	"screen_name":"jqueryHowto",
	"name":"jQuery HowTo",
	"description":"jQuery and javascript howtos, tutorials, hacks, tips and performanace tests. Ask your jQuery questions here...",
	"url":"http://jquery-howto.blogspot.com",
	"followers_count":294,
	"friends_count":120,
	"favourites_count":0,
	"statuses_count":154,
	"location":"",
	"id":26767000,
	"time_zone":"Central Time (US & Canada)",
	"profile_image_url":"http://s3.amazonaws.com/twitter_production/profile_images/110763033/jquery_normal.gif",
	"notifications":false,
	"utc_offset":-21600,
	"following":false,
	"protected":false,
	"created_at":"Thu Mar 26 14:58:19 +0000 2009",
	"profile_link_color":"0000ff",
	"profile_sidebar_fill_color":"e0ff92",
	"profile_background_tile":false,
	"profile_sidebar_border_color":"87bc44",
	"profile_background_color":"9ae4e8",
	"profile_text_color":"000000"
	"profile_background_image_url":"http://static.twitter.com/images/themes/theme1/bg.gif",
}

As you can see the jQuery Twitter API plugin returns Twitter user's avatar URL as well. Using this jQuery plugin you could create another plugin that would return Twitter user's avatar image.

You can see example usage and demo here.

Here is how to use jTwitter:

// I am query data for "jqueryHowto" user
$.jTwitter('jqueryHowto', function(userdata){
  //Callback functn with the user data as shown above
  $('#profile input.url').val(userdata.url);
  $('#profile #avatar').html('<img src="'
       + userdata.profile_image_url + '" />');
});

The first parameter is a Twitter username and the second is a callback function that will be called after jQuery gets user details from the Twitter servers.

Lock user interface plugin – uiLock

I was asked to create a user interface locker using jQuery. The main idea behind was to lock all user interactions with the website while jQuery AJAX loads block contents and unlock when content is loaded. So I thought I would share the code and released it as a jQuery plugin called uiLock.

The plugin extends jQuery and adds two main functions called $.uiLock(); and $.uiUnlock();

Here is how to use uiLock jQuery plugin:

// To lock user interface
$.uiLock();

// To unlock user interface
$.uiUnlock();

$.uiLock(); takes an HTML text argument that will be placed in the page overlay. You can style the overlaying layer using CSS. You can change font color, background color, etc. To style uiLocker use #uiLockId CSS selector.

For example:

#uiLockId{
  background-color:red !important;
}

The plugin demo can be found in the plugin archive. Here is a screenshot of the plugin at work:

uiLock jQuery plugin screenshot

User will not be allowed to interact with the website on the screenshot above. Basically, we are blocking all user actions with an extra layer that uiLock jQuery plugin adds.

Download uiLock jQuery plugin here.

Twitter JSON/JSONP API URL

It is Friday and we don’t want to read long posts and tutorials. So today’s post is going to be short and sweet. I’ve been playing a lot with Twitter lately. I wrote some jQuery and javascript functions that get user details, etc. I will share it with you next week.

But for today, I would like to share Twitter’s JSON and JSONP API URL. I am sharing it because it was hard to find it first. I actually wrote a jQuery plugin that gets Twitter user details using my previous post on cross site AJAX querying method. All Twitter API usage tutorials and articles I found on internet were based on RESTful non JSONP API, so I though I'll share Twitter JSON(P) API with you. Anyway...

Twitter JSON(P) API URL:

http://twitter.com/status/user_timeline/USERNAME.json?count=10
&callback=JSONPcallbackFunction

Here is a code to use with jQuery’s $.getJSON() function:

http://twitter.com/status/user_timeline/USERNAME.json?count=10
&callback=?

We have put ? (question mark) for callback function name so jQuery could replace it with a dynamic one that it has created.

Update: Check out jQuery Twitter API plugin – jTwitter, that uses this Twitter API.

AJAX update content every X seconds

I was asked several times on Twitter how to update some web page section or a block content on a page every x seconds. Some real life examples of this functionality are Twitter search results that come out when there are new tweets with search keyword or bit.ly real time link tracking that updates it’s charts every 5 seconds.

It is clear without saying that we are going to update our page content using AJAX and of course we love AJAX in jQuery flavor. So key to this functionality is JavaScript's built-in setInterval() function. It lets you to run some javascript function every X seconds. For example, the following code would pop alert box every five seconds:

setInterval( "alert('Hello')", 5000 );

Now consider we want to update shouts in our shoutbox every 10 seconds.

function updateShouts(){
    // Assuming we have #shoutbox
    $('#shoutbox').load('latestShouts.php');
}
setInterval( "updateShouts()", 10000 );

The code above will run every 10 seconds (10,000 ms) and update the contents of #shotbox with new shouts.

Get geographical location (geolocation) by IP address using jQuery

Today I came across this post called “IP Address Geolocation Javascript API : JSON”. The author provides you with a free geolocation query URL. The API returns the geographical location of the queried IP address with some additional information such as:

{
	'status':'ok',
	'IP': '74.125.45.100',
	'CountryCode': 'US',
	'CountryName': 'United States',
	'RegionName': 'California',
	'ZipPostalCode': '94043',
	'City': 'Mountain View',
	'Latitude': '37.4192',
	'Longitude': '-122.057'
}

// In case of an error
{
	'status':'parent server not responding'
}

Update: the URL has been changed!

The JSON geolocation querying API’s address is:

http://iplocationtools.com/ip_query.php?output=json&ip=80.80.214.93

The URL above is dead, instead use this one:
http://www.geoplugin.net/json.gp?jsoncallback=?

And the great thing is, you can identify your website visitor’s IP and Geo location by simply querying the API without any parameters like this:

http://iplocationtools.com/ip_query.php?output=json

Knowing your users’ IP and/or location, you might add a behavior to your website that is specific to some location. For example, offering some advertising to US only visitors, or popup with special offer to European users.

Anyway, here is a sample jQuery code to query the API:

// Build the URL to query
var url = "http://iplocationtools.com/ip_query.php?output=json&callback=?&ip=";

// Utilize the JSONP API
$.getJSON(url, function(data){
    if(data['status'] == 'ok'){
        // Do something with the data
        $('#profile #ip')
            .append(data['IP']);
        $('#profile #country')
            .append(data['CountryName']);
    }
});

Here we are not specifying any IP address in the url variable that is why it is getting current user’s data.

Shorten long URLs with jQuery & bit.ly service

I recently signed up to twitter and actively engaging with people who are interested in jQuery. Twitter is a great service and there are all kinds of developers who are sharing interesting links and resources. So it is some kind of interest news group for me. Since you can only have 140 characters in your post, sharing long links limits you. URL shortening services to the rescue. There are lots of free URL shortening services, some are just for long URL shortening, some provide more features like real time click tracking, geostatistics and private URLs.

The great thing about them is that they also provide you with an API. So I thought that there is a way we can make a use of them in our jQuery code. One of the most popular services is bit.ly. You can read more about its API here.

I wrote a simple jQuery code that utilizes the service.

Here is an example:

(function($){
  // set up default options
  var defaults = {
    version:	'2.0.1',
    login:	'bitlyapidemo',
    apiKey:	'R_0da49e0a9118ff35f52f629d2d71bf07',
    history:	'0',
    longUrl:	''
  };

  // Build the URL to query
  var daurl = "http://api.bit.ly/shorten?"
    +"version="+defaults.version
    +"&longUrl="+defaults.longUrl
    +"&login="+defaults.login
    +"&apiKey="+defaults.apiKey
    +"&history="+defaults.history
    +"&format=json&callback=?";

    // Utilize the bit.ly API
    $.getJSON(daurl, function(data){

        // Make a good use of short URL
        $('#myContainer')
            .append(data.results[url].shortUrl);

    });
})(jQuery);

This code does not do much, but I hope you will find a good use of it in your own applications.

jQuery image swap or How to replace an image with another one using jQuery

Swapping one image with another is probably one of the most used javascript techniques. Also Dreamweaver made “image replacement” even easier for non HTML/Javascript programmers by including this feature out of the box. One thing about Dreamweaver’s image swapping javascript is that it’s not the most beautiful javascript code. Well, as always with anything javascript related, jQuery is to the rescue.

jQuery makes dynamic image swapping a peace of cake. All you need to do to replace your image with another one is to replace its src attribute. The browser will take care of the rest.

Here is an example:

$("#myImage").attr("src", "path/to/newImage.jpg");

In the code above we are:

  1. Selecting an image to be replaced;
  2. Changing its src attribute to the new replacer image’s URL.

TIP:
To avoid page jumping and improve user experience it is a good idea to preload your images before you swap them.

Select text in input box on user select or focus

A colleague of mine who is not very javascript (or for that matter jQuery aware) asked me to help him to do a little trick with jQuery. He needed to select the contents of the input box when user selects it (basically, when user focuses in the input field).

In case you're Googler looking for a way of getting input field's value, see the code snippet at the end of the post.

Selecting inputbox text on focus is easy and it's 3 lines of jQuery code. But it adds nice usability touch to your website. This "select all" behavior is browser default when you browse through form fields using TAB key, but when you click on the input text field it does not behave like that.

Here is jQuery code to select text inside an input field on user click or focus.

$("#myInputField").focus(function(){
    // Select input field contents
    this.select();
});

select() is a built in javascript method. It selects content of the field it is called on (in our case, an input field).

We can add this behaviour to all text input fields on the page by extending the jQuery selector.

// Add this behavior to all text input fields
$("input[type=text]").focus(function(){
    this.select();
});

Let's change the selector in the example above event more to add this behavior to all password and textarea fields as well.

// Add this behavior to all text input fields
$("input[type=text], input[type=password], textarea").focus(function(){
    this.select();
});

Also, we can improve our form usability by only selecting the contents of text fields, if their value have not been changed from their default values.

$("input[type=text], textarea").focus(function(){
    // Check for the change from default value
    if(this.value == this.defaultValue){
        this.select();
    }
});

The code above selects all text content of textarea if and only if it's value has changed from its' default value.

Just in case, you came here from search engines looking for a way to get input or textarea's contents, here is how to do it.

// Select the input field & call .val() method
$("input.username").val();

// For textarea, you need to call .html() method instead
$("textarea.comment").html();

How to make jQuery / Prototype / MooTools & others play nicely with Smarty

Smarty is the first template engine I have learned and used in my projects. Smarty makes your PHP code cleaner and promotes the V in MVC. Here is an example of Smarty template:

<html>
<head>
<title>User</title>
</head>
<body>
    User Information:<br />
    Name: {$name}
</body>
</html>

Smarty will replace the {$name} with the variable that you set in your PHP code. Anyway, do you see the problem that might arise when you try to embed your jQuery code or any other javascript library (like Prototype, MooTools, Extjs, etc.) that uses $ as a function name in the <head>?

Smarty parses the file and whenever it encounters the {$ it would try to parse it and replace with the PHP variable like in this example here:

<html>
<head>
<title>User</title>
<script type="text/javascript">
    $(document).ready(function(){
        $(".clazz").css("color", "red");
    });
</script>
</head>
<body>
    User Information:<br />
    Name: {$name}
</body>
</html>

The problem:

Smarty would not care that { and $ are on different lines and would see it like {$(".clazz.... The code above would cause this Smarty error:

Fatal error: Smarty error: [in templateFile.tpl line 5]: syntax error: unrecognized tag: $(".clazz").css("color", "red"); (Smarty_Compiler.class.php, line 455) in C:\PHP\smarty\libs\Smarty.class.php on line 1092

The solution:

There are couple of things you can do about this problem:

  1. Move your javascript (jQuery, Prototype, etc.) code into the external .js file.
  2. Use jQuery() instead of $().
  3. Use Smarty’s {literal}...{/literal} directives to tell Smarty parsing engine that it should not interpret the code within the block.

Example:

Here is how we can rewrite our javascript code above using the 3rd tip:

<html>
<head>
<title>User</title>
<script type="text/javascript">
{literal}
    $(document).ready(function(){
        $(".clazz").css("color", "red");
    });
{/literal}
</script>
</head>
<body>
    User Information:<br />
    Name: {$name}
</body>
</html>

Display loading GIF image while loading through AJAX

Well, let's face it, AJAX is everywhere. Nowadays clients want AJAX "enabled" web applications. They want their web sites to be Web2.0 and that is usually associated with using AJAX. No doubt using AJAX to load parts of your page and use more javascript effects, made easy by jQuery, is a great way to bring your website to life. But we should not forget about our users and the website usability. That is why it is a good practice to display something like text or image that informs users that the content is being loaded or processed.

Now, let's see how can we display a loading image while requested content is being loaded by one of the jQuery's AJAX functions. Here is what happens:

  1. Something triggers AJAX request (like "search" button click);
  2. We put the loading image or a text that ask for user patience to the place where we would later insert the loaded content (or anywhere else);
  3. After remote content is fully loaded, we remove/hide the loading image/text and insert the loaded content.

To make it more apparent, imagine we have HTML page with this markup:

<button id="btnLoad">Load Content</button>
<div id="content">
  Please click "Load Content" button to load content.
</div>

We want to load content when a user clicks on the "Load Content" button. So we need to bind a click event to that button first and make AJAX request only after it is fired.

$("#btnLoad").click(function(){
    // Make AJAX call
    $("#content").load("http://example.com");
});

The above code loads contents from http://example.com into the <div id="content">. While the page is being loaded we want to display our animated GIF image in the "content". So we could further improve our code like so:

$("#btnLoad").click(function(){

  // Put an animated GIF image insight of content
  $("#content").empty().html('<img src="loading.gif" />');

  // Make AJAX call
  $("#content").load("http://example.com");
});

The .load() function would replace our loading image indicator with the loaded content.

Final note:

You might be using jQuery’s other AJAX functions like $.ajax(), $.get(), $.post(), in this case use their callback function to remove loading image/text and append your loaded data.

If you have any question, please tweet me.

Problems with jQuery mouseover / mouseout events

Today I have a quick note for you that will probably save you time someday. Basically it’s a workaround for a bug when you have parent element with children elements and parent element has mouseover or mouseout event. Moving your mouse over children elements may fire mouseout event of their parent. This is caused by event bubbling / propagation and if you would like to have a quick solution just read the solution at the bottom of this post. If you would like to understand it in more details please search Google for event propagation.

The problem:

When you have mouseover and mouseout events bound to some element on you page with children elements. Hovering over children element fires parent’s mouseover and/or mouseout event.

The solution:

The solution to this error is to use mouseenter and mouseleave events instead of mouseover and mouseout.

The reason:

This solution works because mouseover and mouseout events do not bubble from child to parent element.

jQuery AJAX functions (load(), $.get(), etc.) are not loading new page versions problem

Today I would like to share with you a quick solution to the common problem when your AJAX calls to some page that changes over time is not being loaded to your page. In other words, jQuery or your browser is not loading new version of the page.

This problem is common in Mozilla Firefox (FF). Internet Explorer (IE) users I believe, do not experience this problem. Usually it occurs when you use jQuery AJAX functions in javascript setInterval() method. Basically, what happens is that Firefox can not see the changes been made to the page and thinks it’s the same with the old one. So Firefox loads it from cache and you don’t see the new version of your page. To resolve this issue, you should simply add a random string to the request like below.

The solution:

// Reload mypage.html every 5 seconds
var refresh = setInterval(function()
{
    // Minimized code, suggested by Kovacs
    $('#mydiv').load("mypage.htm?" + 1*new Date() );

}, 5000);

Use different CSS rules / styles in JavaScript or jQuery enabled browsers

This is a simple yet very useful and powerful technique. Using different CSS rules in JavaScript or jQuery enabled browsers lets you customize your website style for JS enabled and disabled browsers using only CSS. Thus you separate concerns of styling and business logic into CSS and javascript. This lets you concentrate on your goals and not styling in your javascript code for example.

All you need to do is to add some class or id to body element using javascript/jquery to specify that javascript/jQuery is available. Then define two rules in you CSS files for js enable and disabled browsers.

Here is an example for Javascript enabled browser:

document.getElementsByTagName("body")[0].setAttribute("class", "js");

And in your CSS file:

.someClass{
    display:block;
}
.js .someClass{
    display:none;
}

Why do I need to have a different CSS styles for jQuery/javascript enabled browser you might ask. Consider you have a drop-down menu on your website’s sidebar and you would like to use jQuery/Javascript to make it drop down on mouse hover. You don’t want to hide (display:none) all submenus’ by default. That would make your website not accessible if user has disabled Javascript on his/her browsers.

Similar to previous example, we can use difference CSS style for jQuery enabled browsers.

if(jQuery){
    jQuery("body").addClass("jq");
}

And in your CSS file:

.someClass{
    display:block;
}
.jq .someClass{
    display:none;
}

Check if jQuery plugin is loaded

The previous post checked if jQuery is loaded, now it is time to check if particular jQuery plugin is loaded. Checking if plugin exists or if plugin has been already loaded is useful if you are writing your jQuery code that depends on that plugin.

Here is how to check if some jQuery plugin is loaded or not:

if(jQuery().pluginMethod) {
    //jQuery plugin exists
} else {
    //jQuery plugin DOES NOT exist
}

As you know from previous post on namespacing javascript plugins are created as an additional namespace within jQuery namespace. All you have to do to check if plugin exists is to check if it’s namespace / function is defined.

For example, let’s assume that my plugin depends on jQuery Validation plugin. To check if validation plugin is loaded I would do the following:

if(jQuery().validate) {
    // Validation plugin exists
    // Now I can use $('#someId').validate()
} else {
    // Validation plugin DOES NOT exist
}

Adding and using jQuery on Blogger / Blogspot

Investigating my visitors statistics, I noticed that there were some users who were interested in adding and using jQuery on their Blogger.com (Blogspot.com) accounts. Adding jQuery library to your Blogger/Blogspot blog is not difficult. All you have to do is to add one line of code to your template’s header.

Here is the code to add to your blogger template’s header:

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js" type="text/javascript"></script>

NOTE:
You don’t even need to upload jquery.js file on any other hosting Google will host it for your.

Instruction for adding jQuery to Blogger:

  1. Login to your dashboard;
  2. Choose your blog;
  3. From the top menu select “Layout”;
  4. Then select “Edit HTML” sub-menu;
  5. Add the above code just below <head> tag (or alternatively, just above </head> tag)

Check if jQuery.js is loaded

This article discusses how to check if jquery.js file is loaded. Also, presents a way to force load jQuery file before running any dependant JavaScript code.

In order to determine whether jquery.js file is loaded or not, we need to check for existence of jQuery object. Because, when jquery.js file is loaded, it creates a new global jQuery variable. Checking if some class, method, variable or property does already exist is the very basics of any programming language. In our case, the programming environment is JavaScript and the object we are checking for is jQuery() (or $()).

This method is not limited to jQuery only, you can check existence of any other variable or function in your javascript.

Anyway, as we said earlier, jQuery() or $() functions will only be defined if they are already loaded into the current document. So to test if jQuery is loaded or not we can use 2 methods.

Method 1:

if (window.jQuery) {  
    // jQuery is loaded  
} else {
    // jQuery is not loaded
}

Method 2:

if (typeof jQuery == 'undefined') {  
    // jQuery is not loaded
} else {
    // jQuery is loaded
}

If jquery.js file is not loaded, we can force load it like so:

if (!window.jQuery) {
  var jq = document.createElement('script'); jq.type = 'text/javascript';
  // Path to jquery.js file, eg. Google hosted version
  jq.src = '/path-to-your/jquery.min.js';
  document.getElementsByTagName('head')[0].appendChild(jq);
}

NOTE:
Here we are checking for jQuery function being defined or not. This is a safe way to check for jQuery library being loaded. In case you are not using any other javascript libraries like prototype.js or mootools.js, then you can also check for $ instead of jQuery.

You can also check if particular jQuery plugin is loaded or not.

Dynamically creating input box/checkbox/radio button... does not work in Internet Explorer (IE)

While working on some project, trying to create a checkbox and radio button dynamically using jQuery I came across a problem. Mozilla Firefox, Opera and Safari were creating and rendering my new checkboxes just fine, but Internet Explorer (IE6, IE7) did not create them. I spend half a day trying to figure out what is wrong with my jQuery or JavaScript code. Some hours later, I remember, I came across a post saying that IE can not create a general DOM input form element and then assign it a type (checkbox, radio, text, password, etc) attribute.

What you need to do when you are creating a new checkbox or radio button set with jQuery is to define the type attribute while creating like so:

$('<input type="checkbox" />');
// Create and then set any other attributes
$('<input type="checkbox" />').attr('id', 'newBox');

Problem:

Can not create a new input form fields using jQuery or newly created checkboxes and radio buttons are not displayed/created.

Solution:

To solve the problem you need to create an input field with type attribute already defined.

Only the last element is bound/inserted/etc. in your javascript code’s “for” loop

There is a common problem when you use javascript for loop to bind an event function or add a class that comes from looping selection’s attributes.

To make clear what I mean consider this example:

var lis = $('ul li');

for (var i = 0; i<lis.length; i++) {
    var id = lis[i].id;
    lis[i].onclick = function () {
        alert(id);
    };
} // All li's get and alert the last li's id

There is no obvious code syntax nor logical problem in this code. But you still will get last li’s id in alert window whichever li you click.

The solution to this problem is to rewrite your code similar to this one:

var lis = $('ul li');

for (var i = 0; i<lis.length; i++) {
    var id = lis[i].id;
    lis[i].onclick = function (the_id) {
        return function () {
            alert(the_id);
        };
    }(id);
}

Here, we are introducing another anonymous function which will be called immediately after it has been declared, because of the trailing () (in our case (id)) with the current id.

This solves the problem of all items in the loop getting the last arrays/elements/etc. attribute value (id/class/etc.).

Convert javascript objects into arrays for better performance

jQuery Howto blog has many posts on your javascript  and jQuery code performance. If you have read the last performance post named “5 easy tips on how to improve code performance with huge data sets in jQuery” then you probably got an idea that it’s better to work with arrays for better javascript performance.

The only problem is that jQuery returns an object not an array when you select elements. Consider you have an object with lots of entries and you have to perform some manipulations that are available in javascript array such as reverse, sort, join, etc. Using built in methods is much faster then those you might write yourself. So the best thing would be converting your objects to arrays and jQuery provides utility method that does exactly this – jQuery.makeArray(obj).

// From jQuery Documentation
var arr = jQuery.makeArray(document.getElementsByTagName("div"));
arr.reverse(); // use an Array method on list of dom elements
$(arr).appendTo(document.body);

Preload images with jQuery

Web2.0 came with AJAX and AJAX came with its own requirements and standards for web application developers. Now web applications are more like desktop applications with a lot of options, dialogs and more. If you have developed AJAX application with different user controls you surely loaded resources such images, other javascript files on demand. This helps you keep your application lightweight and makes its load time faster.

jQuery makes creation and loading DOM elements (in our case images) very easy. If you need to preload an image you can use this jQuery script here:

// Create an image element
var image1 = $('<img />').attr('src', 'imageURL.jpg');

First jQuery creates a image DOM element and setting the src attribute of the image element would tell the user browser to load that image. Thus preloading the image.

Next you should insert your DOM element into the DOM tree using one of the many jQuery DOM manipulation methods.

Here are some examples of how you could insert preloaded image into your website:

var image1 = $('<img />').attr('src', 'imageURL.jpg');

// Insert preloaded image into the DOM tree
$('.profile').append(image1);
// OR
image1.appendTo('.profile');

But the best way is to use a callback function, so it inserts the preloaded image into the application when it has completed loading. To achieve this simply use .load() jQuery event.

// Insert preloaded image after it finishes loading
$('<img />')
    .attr('src', 'imageURL.jpg')
    .load(function(){
        $('.profile').append( $(this) );
        // Your other custom code
    });

Similar how to’s: