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:

How to add more items to the existing jQuery selection

There are occasions when you have already selected elements and need to add more items to it. Imagine you have selected different items and have jQuery selection object. For example:

var elms = $('#elem, .items');

Now, you need to add more new items (DOM nodes) to your section. Let’s say you want to add .otherItems to your elms selection. You could achieve it by using one of these methods:

elms.add('.otherItems');
$('.otherItems').add(elms); // The same as above

The post title for the second method would be “How to add jQuery object/selection to the existing selection”. Anyway, it’s just wording :)

jQuery For Firebug

We all use Firebug and sometimes need jQuery in pages that don’t already have it. In such cases you can use the following javascript code or the bookmarklet that would insert jQuery into the page’s DOM on the fly. Thus making jQuery available for use in Firebug.

Load jQuery to Firebug

Here are two options to jQuerify any page. The code is taken from a jQuerify javascript code snippet by John Resig.

Method 1: You can run this code to make jQuery available in Firebug:

var s = document.createElement('script');
s.setAttribute('src', 'http://ajax.googleapis.com/ajax/libs/jquery/1.3.1/jquery.min.js');
document.body.appendChild(s);
s.onload=function(){
    /*Your Code Here*/
};
void(s);

Method 2: Or you can drag this bookmarklet to your browser’s bookmarks toolbar:

  • Load jQuery – When you click on this link it will load jQuery from Google’s server and make it available in Mozilla add-on Firebug.

Add table row using jQuery and JavaScript

I noticed that there are a lot of developers who need to dynamically add a new table row to the bottom of their tables. I wrote a little javascript function that takes your jQuery selection of tables and dynamically adds a table row at the bottom of them.

jQuery add table row function definition:

/*
    Add a new table row to the bottom of the table
*/

function addTableRow(jQtable){
    jQtable.each(function(){
        var $table = $(this);
        // Number of td's in the last table row
        var n = $('tr:last td', this).length;
        var tds = '<tr>';
        for(var i = 0; i < n; i++){
            tds += '<td>&nbsp;</td>';
        }
        tds += '</tr>';
        if($('tbody', this).length > 0){
            $('tbody', this).append(tds);
        }else {
            $(this).append(tds);
        }
    });
}

jQuery add table row function usage example:

addTableRow($('#myTable'));
addTableRow($('.myTables'));

How to use YUICompressor to compress your javascript code?

Since writing on this blog I posted two jQuery plugins and I needed to compress my js files. So as jQuery documentation suggests I used YUICompressor. YUICompressor is javascript and CSS file/code compressor written in Java language. So to run one yourself you will need JRE installed on your machine.

Then call this command:

java -jar /path/to/yuicompressor.jar path/to/file.js -o path/to/minimized.file.js

Your file will be compressed and saved to path you specified as the last parameter (in our case minimized.file.js).

Links:

  1. Download YUICompressor
  2. Download JRE (required to run java applications)
  3. Online version of YUICompressor

Font cleartype problems with fadeIn() and fadeOut() in Internet Explorer 7 (IE7)

Have you ever noticed whenever you use jQuery's fadeIn() and fadeOut() functions your text will become edgy. Mozilla and other seem to be rendering fine (not sure about IE6). Anyway, to solve this problem you need to remove the filter attribute from the DOM element that you have faded in/out.

For example:

// This causes this text glich
$("#message").fadeIn();

// This will fix it
document.getElementById("#message").style.removeAttribute("filter");

Screenshots:

SS-20090216194727

SS-20090216194422 

You need to remove the filter attribute after fadeIn() function has completed its job. In other words, as a function callback. Otherwise, fadeIn()/fadeOut() functions would change the opacity of the element, which in turn would cause the filter attribute to be attached yet again. So, remove the attribute in function callback like this:

$('#message').fadeIn(function(){
    this.style.removeAttribute("filter");
});

Add code highlighter to Blogger (Blogspot)

If you maintain a blog related to programming languages, you most definetly provide example code. Adding syntax highlighting to your code makes it more readable and easier to understand. In this post you will learn how to add a code highlighter to your blog on Blogger (blogspot.com).

Before we start we have to choose a code hightlighter library. We have to choose a highlighting library that does highlighting in the browser and hosted on some the server. Because Blogger does not allow custom plugins that does processing (on the server side) and does not allow uploading javascript files.

Here is a list of popular syntax highlighters:

  • Google Code Prettify - Developed and used by Google Code project. Lightweight, hosted on the Google server and used on this blog.

  • SyntaxHighlighter - Probably the most popular and feature rich highlighter. Used by Apache, Mozilla, Yahoo!. You can find links to hosted versions.

  • Highlight.js - Lightweight, themable highlighter.

First, you have to choose library to use. This blog uses lightweight "Google Code Prettify", so I will be using the it in the exmaples below. But the process of adding it to your blog is the same for any other library. Once you made a choice, find a hosted file for that library.

Here is a link to the file from Google Code Project page:

http://google-code-prettify.googlecode.com/svn/loader/run_prettify.js

<!-- Also hosts file on secure connection -->
https://google-code-prettify.googlecode.com/svn/loader/run_prettify.js

Add highlighter to Blogger

In order to add the hightlighter to your blog, follow this step:

  1. Login to your account

  2. Navigate to: Your blog » Template » Edit HTML

  3. Just before the closing </body> tag add this code

    <script src='http://google-code-prettify.googlecode.com/svn/loader/run_prettify.js'/>
    <script type='text/javascript'>prettyPrint();</script>
    </body>
  4. Click on "Save Template"

  5. Done

NOTE:
Do not forget to backup your template before making any changes.

You have successfully added Google Code Prettify syntax highlighter to your blog. Now in order to highlight your code wrap it into <pre class="prettyprint">...</pre> or <code class="prettyprint">...</code> tags.

Example

Here is an example of Code highlighter in use.

function JavascriptFunction() {
    // Comment example
    var myVariable;

    var privateMethod = function(){ };

    return myVariable;
}

// jQuery code sample
$.extend({ 
    myNamespaced: function(myArg){ 
        return 'namespaced.' + myArg; 
    } 
}); 
$.myNamespaced('A'); // Another comment

How to get a YouTube video screenshot image (thumbnail) URL using JavaScript

YouTube is a great video service by Google. As with any other product Google makes it easy to use its content on your own site. You can embed a YouTube video on your own site or query YouTube API (if you have a developer key). But what if you don't want to embed a flash video player and you only need an image of the video. The following function returns a YouTube video's thumbnail URL. Nothing more, nothing less.

Update: Now available as jQuery YouTube plugin – jYouTube.

The javascript function:

function getScreen( 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 can pass a YouTube video URL or video id and the function will return a path to the video image. The second function argument is optional. You can specify the size of returned image. It can be big (320x240) or small (128x96), defaults to big.

Here is an example usage:

imgUrl_big   = getScreen("uVLQhRiEXZs"); 
imgUrl_small = getScreen("uVLQhRiEXZs", 'small');
See the plugin in action on jQuery YouTube demo page.

How to set custom rules in jQuery Validation plugin for fields that have a period "." in their names

We all love and use jQuery Validation plugin. For basic forms it does a great job and works flawlessly 80% of the time. But we all work on different kinds of projects and validation requirements change project to project.

jQuery Validation is a very flexible plugin and provides a way to easily define your own validation rules. You can read more about jQuery Validation plugin and custom validation rules here. It is quite straight forward.

Anyway, I was working on a project that requires the use of custom rules and I had no control over the generated HTML code and used CSS selectors. So I had to work with CSS classes that had period "." symbol in their names. My first attempt failed.

Here is the code that failed. Pay attention to the selector name with the (.) in it's name.

rules: { 
    user.email: { 
        required: true, 
        email: true 
    } 
} 

It is common in Java programming world that your form fields have periods (.) in their names and this is an example of that. So to solve the problem all you have to do is to make the object key a string like this:

rules: { 
    "user.email": { 
        required: true, 
        email: true 
    } 
} 

This will solve your problem and let you get on with your project. Happy coding...

5 easy tips on how to improve code performance with huge data sets in jQuery

Sitting on jQuery's support mailing list I noticed that developers use jQuery with huge data sets and their code becomes very slow. Examples would be generating very long tables with a lot of rows using AJAX to get JSON data. Or iterating through a long (very long) list of data, etc.

So I compiled a list of 5 easy tips on how to improve your code performance while working with huge data sets in jQuery.

  1. Use JavaScript native for() loop instead of jQuery's $.each() helper function.

    Native browser functions are always faster then any other helper functions that were built to add an abstraction layer. In case you are looping through an object that you have received as JSON, I highly recommend you rewrite your JSON to contain an array rather than an object.

  2. Do NOT append an element to the DOM in your loop.

    This one is probably one of the most important tips that will significantly improve your code performance. It is so important that I will repeat myself. Do not append a new element to the DOM in your loop statement. Instead store it in a variable as text and append it to the DOM after your loop finishes like this:

    // DO NOT DO THIS 
    for (var i=0; i<=rows.length; i++)  
    { 
        $('#myTable').append('<tr><td>'+rows[i]+'</td></tr>'); 
    } 
    
    // INSTEAD DO THIS 
    var tmp = ''; 
    for (var i=0; i<=rows.length; i++)  
    { 
        tmp += '<tr><td>'+rows[i]+'</td></tr>'; 
    } 
    $('#myTable').append(tmp);

  3. If you have a lot of elements to be inserted into the DOM, surround them with a parent element for better performance.

    When you have a lot of elements to insert into the DOM tree it takes time to add them all. Somehow adding one element with 1000 children is faster than adding 1000 children separately. You can search this site for performance tests that prove it.
    So, to improve our previous example's performance let's cover <tr>'s with <tbody> tag like this:

    var tmp = '<tbody>';
    for (var i=0; i<=rows.length; i++)
    {
        tmp += '<tr><td>'+rows[i]+'</td></tr>';
    }
    tmp += '</tbody>';
    $('#myTable').append(tmp);

  4. Don't use string concatenation, instead use array's join() method for a very long strings.

    var tmp = [];
    tmp[0] = '<tbody>';
    for (var i=1; i<=rows.length; i++)
    {
        tmp[i] = '<tr><td>'+rows[i-1]+'</td></tr>';
    }
    tmp[tmp.length] = '</tbody>';
    $('#myTable').append(tmp.join(''));

  5. And the last but not least use setTimeout() function for your long list looping and concatenation functions.

    This will make sure that page does not freeze while it loops through the long list of data and lets users to work with your page meanwhile.

    It was well mentioned in comments that setTimeout() function should be used to split your code processing into little chunks so your browser does not freeze up like this:

    function myFunk(data){ 
         
        // do processing 
         
        if(!has_finished) 
            setTimeout("myFunk()", 100); 
    }

How to check jQuery version?

This post will show you how to check currently loaded jQuery version on the page. This maybe useful in your jQuery plugins, in cases when your code utilizes jQuery version specific methods. Also, when you are writing code that runs in an environment where jQuery is already embedded. For example in open source CMS's like Drupal, Magento Ecommerce, etc.

jQuery keeps track of the current version of the script being used in jQuery.fn.jquery property. Both major version version 1.x and version 2.x have this property.

 // Returns string: "1.10.2"
jQuery.fn.jquery;

// Since jQuery == $, we can use shorthand syntax
$.fn.jquery;

You can look into the jQuery source code and find out that jQuery.fn is a reference to jQuery.prototype.

jQuery.fn = jQuery.prototype = {
 // The current version of jQuery being used
 jquery: version,
...

This means we can use alternative method to get current jQuery version like so:

// Alternative method, also returns string
jQuery().jquery;

// or shorthand method
$().jquery

Caveats & notes

I would like to remind you that jQuery must be loaded before you call the code above. Otherwise, it will throw an error: ReferenceError: jQuery is not defined or TypeError: $(...) is null. To avoid it, you can check for existance of jQuery first.

if (window.jQuery) {  
  jQuery().jquery;
}

If jQuery is not loaded, we can load it dynamically from an alternative location.

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

Also, learn how to check loaded jQuery UI version.

How to disable all jQuery animations at once

Yesterday I came across jQuery.fx.off setting in jQuery documentation. It disables all jQuery animations effective immediately when you set it's value to true.

Consider this code:

jQuery.fx.off = true;

$("input").click(function(){
  $("div").toggle("slow");
});

Your div will be showed/hidden immediately without animation. One of the reasons (as documentation mentions) to disable animations would be "slow" environments.

How to get full html string including the selected element itself with jQuery's $.html()

Sometimes you need to get the selected element's html as well when using .html() function. To make it more clear what I mean, consider you have this HTML markup:

<div id="top">
  <div id="inner">
    Some content
  </div>
  More content
</div>

And you need to get not only <div id="inner">Some con... but <div id="top"><div id="inner">Some con...

Here is the code to get jQuery selector's HTML including its own:

var html = $('<div>').append($('#top').clone()).remove().html();

Here we are:

  1. Cloning selected div
  2. Creating a new div DOM object and appending created clone of the div
  3. Then getting the contents of wrapped div (which would give us all HTML)
  4. Finally removing the created DOM object, so it does not clutter our DOM tree.

This is a little trick you can use to select self HTML with jQuery's .html() function. But if you can you should surround your markup with some dummy div and avoid this workaround all together. This would be much faster since jQuery would not need to do all the DOM manipulations.