Enabling The Use Of delay() In Pre jQuery 1.4

Monday, January 24, 2011 - 13:58

The other day I was trying to convert a HTML template into a CMS system and I found a stumbling block with the use of the jQuery function delay() in the template's JavaScript. During part of the templating process I found the following error occurring on the page.

1
Uncaught TypeError: Object #<an Object> has no method 'delay'

The error appeared to be comming from the jQuery core and the fact that it couldn't find a method called delay(). Looking at the delay() manual page I could see that it was only included in jQuery 1.4 and so was causing an error as the method didn't exist in the version of jQuery I was using. The problem here was that I was using Drupal 6 as the CMS, which has jQuery 1.2.6. Even with third party solutions like the jQuery update module in place I couldn't quite get up to the needed version. So I had to find a way to include delay() without upgrading jQuery to version 1.4.

The solution is to add a jQuery.fn.extend statement to your JavaScript page library so that the delay() method is available to the rest of the code on the page. Below is the code that creates the delay() method and can be placed anywhere on the page, although it is probably best to put it in your main JavaScript file.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
/**
 * Add in the extend function, added in Jquery 1.4 (which we don't have)
 */
jQuery.fn.extend({
        // Based off of the plugin by Clint Helfers, with permission.
        // http://blindsignals.com/index.php/2009/07/jquery-delay/
        delay: function( time, type ) {
                time = jQuery.fx ? jQuery.fx.speeds[time] || time : time;
                type = type || "fx";
 
                return this.queue( type, function() {
                        var elem = this;
                        setTimeout(function() {
                                jQuery.dequeue( elem, type );
                        }, time );
                });
        }
});

You can now use the following code without any errors.

1
$("div.first").slideUp(300).delay(800).fadeIn(400);
Category: 
philipnorton42's picture

Philip Norton

Phil is the founder and administrator of #! code and is an IT professional working in the North West of the UK.
Google+ | Twitter

Comments

Same problem with OpenCms. Thanks a lot for your solution!!!

Extremely helpful tip -- thanks for sharing. I spent ages mucking around with this before realizing that delay() isn't available in drupal 6.x...

Add new comment