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.