Awesome jQuery Tricks

Awesome jQuery Tricks

As we all know, jQuery is an awesome library and has transformed the internet as we know it. In this article we will cover 5 extremely useful jQuery tricks that you can use in your sites. Let’s get started.

Gracefully Degrade Broken Images
Broken images can be a pain to deal with. They degrade the user experience and can be difficult to find without scanning your site regularly with a 3rd party tool. Luckily it’s easy to substitute broken images with an image that you specify using jQuery. the error callback of an image gets fired any time an image can’t be successfully loaded by the browser. For example:

1
2
3
$('img').error(function(){
  $(this).attr('src', 'images/missing.png);
});

The code above would replace any broken images with an image in the images folder called missing.png. You could also do something like make an AJAX request to your server to log the location of the broken image.

Wait For an Image to Be Loaded
Sometimes you need to wait for an image to be loaded before continuing to process events. This is most often useful with libraries like the jQuery Masonry library, where images can affect the size of the overall content. Fortunately this is easy with the load callback. For example:

1
2
3
$('img').load(function() {
  // Do stuff here...
});

The above code would wait for the image to be loaded and then execute the code specified in the callback.

Zebra Stripe a Table
Sometimes we want our tables to alternating odd/even colors. While this is possible using CSS3, older browsers don’t support most CSS3 features. Using this script allows our tables to be striped across all browsers.

1
2
3
$('table tr:even').css('background', '#f7f7f7'); // Strip every even row
$('table tr:odd').css('background', '#f7f7f7'); // Stripe every odd row
$('table > tbody > tr:even').css('background', '#f7f7f7'); // Only stripe the table body

The above code will do striping as noted in the comments.

Preloading Images
If your page uses a lot of images that aren’t visible initially, it might be worth it to preload them. This simple script listed below does exactly that.

1
2
3
4
5
6
7
$.preloadImages = function() {
  for (var i = 0; i < arguments.length; i++) {
    $("<img />").attr("src", arguments[i]);
  }
}

$.preloadImages("images/myimage1.jpg","images/myimage2.jpg");

Detect Mobile Devices
Sometimes we need a ‘check all’ checkbox for our web pages that selects every checkbox in a fieldset. The code below lets you easily accomplish this.

1
2
3
$('.checkall').click(function () {
  $(this).parents('fieldset:eq(0)').find(':checkbox').attr('checked', this.checked);
});

So far so good, That’s it!!! See ya!!! :)