Showing posts with label tutorial. Show all posts

jQuery .end() explanation & examples

jQuery's .end() method is one of the most rarely used methods that I know of. In this post I would like share remind you what it does and how we can use it to make our jQuery code more readable.

Firstly, what does it do?

Put simply .end() cancels the last filtering action and returns a set like it was before the filtering was applied. It's best explained with an example. Consider we have this HTML code:

<ul>
  <li>One</li>
  <li>Two</li>
  <li class="special">>Three</li>
</ul>
$('li')  // would have all 3 elements

$('li').filter('.special')  // would have 1 (third) element only

$('li').filter('.special').end()  // would have all 3 elements again

Now, the main question: Why on earth would you need it?! It is actually very useful when you have to apply different methods on several sub-selections in your DOM. The game development fits this case perfectly. I have seen beautiful and easy to understand game code that was made possible by a combination of custom jQuery selectors, extending jQuery and .end() method.

Couple of examples

To give you an idea of what a code of some hypothetical game might look like:

check_mines = function(from, to_coord){  // don't pay attention to this building block
     $("#game-canvas")

          .find("div:ships")
               .moveElements(from, to_coord)
          .end()

          .find("div:mines")
               .killIfClose(to_coord)
          .end()

          .find("div:healthPack")
               .addHealthIfClose(to_coord)
               .markHealthPackUsed(to_coord)
          .end();

};
SomeGame.register(check_mines);  // don't pay attention to this building block

As you can see, .end() helps us group related actions and make the code more readable.

Let's consider more realistic case. Let's say we have an article with images, links etc. (eg. Wikipedia articles). We need to add .content-img class to all images, than add .external-link to all external links, and finally apply a tooltip plugin to all the links that have .tooltip class within the article.

<div class="article">
     <p>Text ... </p>
     ...
</div>
$(".article")

    .find("img")
        .addClass("content-image")
    .end()  // back to .article set

    .find("a:external")
        .addClass("external-link")
    .end() // back to .article set

    .find("a.tooltip")
        .tooltip()
    .end(); // don't really need it here, but nice to have for symmetry

The above case is better written in 3 separate lines of codes of course, but it here to help explain the purpose of the .end().

NOTE:
If you do several filtering, you must call .end() several times as well.

$(".article").find("a").filter(".tooltip").end().end();

Hope you will find useful cases for .end() in your projects.

Check if a language file is loaded for jQuery Globalization plugin

Recently, I wrote my first jQuery Globalization plugin introductory post. I mentioned that I will write a tutorial for Globalization plugin and I am. While writing the tutorial I thought I’ll write one of my short Friday jQuery tips.

In this post you will learn how to check if a specific jQuery Globalization plugin language file is loaded or not. Globalization plugin saves localization data and all information in jQuery.cultures object. By default English language is added. So if you add "Inuktitut" language (code iu) the jQuery.cultures object will be extended and will have jQuery.cultures.iu object in it.

So to check if particular language file is loaded all we need to do is to check if jQuery.cultures.langCode is defined. Here is an example:

if($.cultures.iu){
    // Inuktitut jquery.glob.iu.js lang file is loaded
}else {
    // Inuktitut language is not loaded, load it here
}

Some cultures have different alphabet, so they will have that appended in their language and culture names. For example Inuktitut has Syllabics (iu-Cans) and Latin alphabets (iu-Latn), So you will not be able to check the file existence with the code above. Here is a syntax to do it:

if($.cultures.iu-Latin){
    // Will not work
}

// Better way to check if the lang file is loaded
if($.cultures["iu-Latn"]){
    // Inuktitut jquery.glob.iu-Latn.js lang file is loaded
}else {
    // Inuktitut language is not loaded, load it here
}

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.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.

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

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.

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.

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.

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