jQuery 1.4 Released: What you Must Know

jQuery 1.4 Released: The 15 New Features you Must Know

jQuery 1.4 was recently released. This wasn’t simply a maintenance release as some had speculated; there are many new features, enhancements and performance improvements included in 1.4! This post covers the new features and enhancements that you may find beneficial.

You can download jQuery 1.4 right now, here: http://code.jquery.com/jquery-1.4.js

1. Passing Attributes to jQuery(…)

Pre 1.4, jQuery supported adding attributes to an element collection via the useful "attr" method, which can be passed both an attribute name and value, or an object specifying several attributes. jQuery 1.4 adds support for passing an attributes object as the second argument to the jQuery function itself, upon element creation.

Let’s say you need to create an anchor element with several attributes. With 1.4 it’s as simple as:

jQuery('<a/>', {
    id: 'foo',
    href: 'http://google.com',
    title: 'Become a Googler',
    rel: 'external',
    text: 'Go to Google!'
});

You may have noticed the "text" attribute— you’ll probably be wondering what that’s doing there, after all there’s no "text" attribute for anchors! Well, jQuery 1.4 utilises its very own methods when you pass certain attributes. So the “text” attribute specified above would cause jQuery to call the ".text()" method, passing "Go to Google!" as its only argument.

A better example of this in action:

jQuery('<div/>', {
    id: 'foo',
    css: {
        fontWeight: 700,
        color: 'green'
    },
    click: function(){
        alert('Foo has been clicked!');
    }
});

The "id" is added as a regular attribute, but the "css" and "click" properties trigger calling of each respective method. The above code, before the 1.4 release, would have been written like this:

jQuery('<div/>')
    .attr('id', 'foo')
    .css({
        fontWeight: 700,
        color: 'green'
    })
    .click(function(){
        alert('Foo has been clicked!');
    });

Read more about jQuery(…)

2. Everything “until”!

Three new methods have been added to the DOM traversal arsenal in 1.4, "nextUntil", "prevUntil" and "parentsUntil". Each of these methods will traverse the DOM in a certain direction until the passed selector is satisfied. So, let’s say you have a list of fruit:

<ul>
    <li>Apple</li>
    <li>Banana</li>
    <li>Grape</li>

    <li>Strawberry</li>
    <li>Pear</li>
    <li>Peach</li>
</ul>

You want to select all of items after "Apple", but you want to stop once you reach "Strawberry". It couldn’t be simpler:

jQuery('ul li:contains(Apple)').nextUntil(':contains(Pear)');
// Selects Banana, Grape, Strawberry

Read more about: prevUntil, nextUntil, parentsUntil

3. Binding Multiple Event Handlers

Instead of chaining a bunch of event binding methods together, you can lump them all into the same call, like so:

jQuery('#foo).bind({
    click: function() {
        // do something
    },
    mouseover: function() {
        // do something
    },
    mouseout: function() {
        // do something
    }
})

This also works with ".one()".

Read more about .bind(…)

4. Per-Property Easing

Instead of just defining one easing function for a single animation, you can now define a different easing function for each property that you’re animating. jQuery includes two easing functions, swing (the default) and linear. For other ones you’ll need to download them separately!

To specify an easing function for each property simply define the property as an array, with the first value being what you want to animate that property to, and the second being the easing function to use:

jQuery('#foo').animate({
    left: 500,
    top: [500, 'easeOutBounce']
}, 2000);

See this code in action!

You can also define per-property easing functions in the optional options object as property name-value pairs in the "specialEasing" object:

jQuery('#foo').animate({
    left: 500,
    top: 500
}, {
    duration: 2000,
    specialEasing: {
        top: 'easeOutBounce'
    }
});

Editor’s Note – The author of this article, James Padolsey, is being modest. This new feature was his idea!

Read more about per-property easing

5. New Live Events!

jQuery 1.4 adds support for delegating the "submit", "change", "focus" and "blur" events. In jQuery, we use the ".live()" method to delegate events. This is useful when you have to register event handlers on many elements, and when new elements may be added over time (using ".live()" is less-costly than re-binding continually).

But, be careful! You must use the event names, "focusin" and "focusout" if you want to delegate the "focus" and "blur" events!

jQuery('input').live('focusin', function(){
    // do something with this
});

6. Controlling a Function’s Context

jQuery 1.4 provides a new "proxy" function under the jQuery namespace. This function takes two arguments, either a "scope" and a method name, or a function and the intended scope. JavaScript’s "this" keyword can be quite tricky to keep a hold of. Sometimes you won’t want it to be an element, but instead an object that you’ve previously created.

For example, here we’ve got an "app" object which has two properties, a "clickHandler" method and a config object:

var app = {
    config: {
        clickMessage: 'Hi!'
    },
    clickHandler: function() {
        alert(this.config.clickMessage);
    }
};

The "clickHandler" method, when called like "app.clickHandler()" will have "app" as its context, meaning that the "this" keyword will allow it access to "app". This works quite well if we simply call:

app.clickHandler(); // "Hi!" is alerted

Let’s try binding it as an event handler:

jQuery('a').bind('click', app.clickHandler);

When we click an anchor it doesn’t appear to work (nothing is alerted). That’s because jQuery (and most sane event models) will, by default, set the context of the handler as the target element,- that is, the element that’s just been clicked will be accessible via "this". But we don’t want that, we want "this" to be set to "app". Achieving this in jQuery 1.4 couldn’t be simpler:

jQuery('a').bind(
    'click',
    jQuery.proxy(app, 'clickHandler')
);

Now whenever an anchor is clicked, “Hi!” will be alerted!

The proxy function returns a "wrapped" version of your function, with "this" set to whatever you specify. It’s useful in other contexts too, such as passing callbacks to other jQuery methods, or to plugins.

Read more about jQuery.proxy

7. Delay an Animation Queue

You can now add a delay to your animation queues. In fact, this works on any queue, but its most common use case will probably be with the "fx" queue. This allows you to pause between animations without having to mess with callbacks and calls to "setTimeout". The first argument to ".delay()" is the amount of milliseconds you want to delay for.

jQuery('#foo')
    .slideDown() // Slide down
    .delay(200) // Do nothing for 200 ms
    .fadeIn(); // Fade in

If you want to delay a queue other than the default "fx" queue, then you’ll need to pass the queue name as the second argument to ".delay()".

Read more about .delay(…)

8. Check if an Element Has Something

jQuery 1.4 makes it easy to check if an element (or collection) ".has()" something. This is the programmatic equivalent to jQuery’s selector filter, ":has()". This method will select all elements in the current collection that contain at least one element that complies with the passed selector.

jQuery('div').has('ul');

That would select all DIV elements that contain UL elements. In this situation you’d probably just use the selector filter (":has()"), but this method is still useful when you need to filter a collection programmatically.

jQuery 1.4 also reveals the "contains" function under the jQuery namespace. This is a low-level function that accepts two DOM nodes. It’ll return a boolean indicating whether the second element is contained within the first element. E.g.

jQuery.contains(document.documentElement, document.body);
// Returns true - <body> is within <html>

Read more about: .has(…), jQuery.contains(…)

9. Unwrap Elements!

We’ve had the ".wrap()" method for a while now. jQuery 1.4 adds the ".unwrap()" method which does the complete opposite. If we assume the following DOM structure:

<div>
    <p>Foo</p>
</div>

We can unwrap the paragraph element like so:

jQuery('p').unwrap();

The resulting DOM structure would be:

<p>Foo</p>

Essentially, this method simply removes the parent of any element.

Read more about .unwrap(…)

10. Remove Elements Without Deleting Data

The new ".detach()" method allows you to remove elements from the DOM, much like the ".remove()" method. The key difference with this new method is that it doesn’t destroy the data held by jQuery on that element. This includes data added via ".data()" and any event handlers added via jQuery’s event system.

This can be useful when you need to remove an element from the DOM, but you know you’ll need to add it back at a later stage. Its event handlers and any other data will persist.

var foo = jQuery('#foo');

// Bind an important event handler
foo.click(function(){
    alert('Foo!');
});

foo.detach(); // Remove it from the DOM

// … do stuff

foo.appendTo('body'); // Add it back to the DOM

foo.click(); // alerts "Foo!"

Read more about .detach(…)

11. index(…) Enhancements

jQuery 1.4 gives you two new ways to use the ".index()" method. Previously, you could only pass an element as its argument and you’d expect a number to be returned indicating the index of that element within the current collection.

Passing no arguments now returns the index of an element amongst its siblings. So, assuming the following DOM structure:

<ul>
    <li>Apple</li>
    <li>Banana</li>
    <li>Grape</li>

    <li>Strawberry</li>
    <li>Pear</li>
    <li>Peach</li>
</ul>

When a list item is clicked you want to find out the index of the clicked element amongst all the other list items. It’s as simple as:

jQuery('li').click(function(){
    alert( jQuery(this).index() );
});

jQuery 1.4 also allows you to specify a selector as the first argument to ".index()", doing so will give you the index of the current element amongst the collection produced from that selector.

You should note that what’s returned from this method is an integer, and it will return -1 if the selector/element passed cannot be found in the document.

Read more about .index(…)

12. DOM Manipulation Methods Accept Callbacks

Most of the DOM manipulation methods now support passing a function as the sole argument (or second, in the case of ".css()" & ".attr()"). This function will be run on every element in the collection to determine what should be used as the real value for that method.

The following methods have this capability:

Within the callback function, you’ll have access to the current element in the collection via "this" and its index via the first argument.

jQuery('li').html(function(i){
    return 'Index of this list item: ' + i;
});

Also, with some of the above methods you’ll also get a second argument. If you’re calling a setter method (like ".html()" or ".attr('href)") you’ll have access to the current value. E.g.

jQuery('a').attr('href', function(i, currentHref){
    return currentHref + '?foo=bar';
}); 

As you can see, with the ".css()" and ".attr()" methods, you would pass the function as the second argument, since the first would be used to name the property you wish to change:

jQuery('li').css('color', function(i, currentCssColor){
    return i % 2 ? 'red' : 'blue';
});

13. Determine the Type of Object

jQuery 1.4 adds two new helper functions (stored directly under the jQuery namespace) that help you determine what type of object you’re dealing with.

First, there’s "isEmptyObject", this function returns a boolean indicating whether or not the the passed object is empty (devoid of properties – direct and inherited). Second, there’s "isPlainObject", which will return a boolean indicating whether the passed object is a plain JavaScript object, that is, one created via "{}" or "new Object()".

jQuery.isEmptyObject({}); // true
jQuery.isEmptyObject({foo:1}); // false

jQuery.isPlainObject({}); // true
jQuery.isPlainObject(window); // false 
jQuery.isPlainObject(jQuery()); // false

Read more about: isPlainObject(…), isEmptyObject(…)

14. Closest(…) Enhancements

jQuery’s ".closest()" method now accepts an array of selectors. This is useful when you want to traverse the ancestors of an element, looking for (more than one) closest elements with certain characteristics.

In addition, it now accepts a context as the second argument, meaning that you can control just how far or how close you want the DOM traversed to. Both of these enhancements accommodate rare use cases but they are used internally to great effect!

Read more about .closest(…)

15. New Events! focusIn and focusOut

As mentioned, to delegate the "focus" and "blur" events you must use these new events, called "focusin" and "focusout". These events allow you to take action when an element, or a descendant of an element, gains focus.

jQuery('form')
    .focusin(function(){
        jQuery(this).addClass('focused');
    });
    .focusout(function(){
        jQuery(this).removeClass('focused');
    });

You should also note that both of these events do not propagate ("bubble"); they are captured. This means that the outermost (ancestor) element will be triggered before the causal "target" element.

Read more about the focusIn and focusOut events.

Enjoy jQuery 1.4, the most anticipated, most feature-rich, best performing release of jQuery yet!

Well, that’s it! I’ve tried to cover the changes which I think will have an impact on you!

If you haven’t already, you should check out the "14 days of jQuery", an awesome online event marking the release of jQuery 1.4, and jQuery’s fourth birthday!

And don’t forget to checkout the new API documentation!

Write a Plus Tutorial

Did you know that you can earn up to $600 for writing a PLUS tutorial and/or screencast for us? We’re looking for in depth and well-written tutorials on HTML, CSS, PHP, and JavaScript. If you’re of the ability, please contact Jeffrey at nettuts@tutsplus.com.

Please note that actual compensation will be dependent upon the quality of the final tutorial and screencast.

Write a PLUS tutorial

James Padolsey is JimmyP on Codecanyon
Tags: jQuery
Note: Want to add some source code? Type <pre><code> before it and </code></pre> after it. Find out more
  • http://www.philohermans.com Philo

    Great list! Great Features! :)

  • http://parenting.pl Marcin

    I am still trying to get my head over 1.3, but I like the new traversal features of 1.4.

    And thanks for the immediate update on new features – that was really quick.

    • Shuuun

      hehe, when i would use all features of the latest release, or could use them right i would be happy. Now we got even more stuff to learn and combine :D
      My weekends will lose more and more freetime^^

      But jquery is the most usable library for js in my eyes :) <3

  • http://michael.theirwinfamily.net Michael

    Wow! I’m liking the until selector, delay, and the ability to bind multiple “binds” at the same time!

  • http://www.webtrindade.com.br Jônatan Fróes

    wow! jQuery rocks!

  • http://www.jlapitan.com jlapitan

    nice.. i love that “Everything until” and the new Live Events..

    i’ve only use .live() a couple of days ago while looking for a solution on how to paginate inside jqueryui tabs. hehe…

  • http://www.imblog.info Muhammad Adnan

    I liked the focus in and out. Anyways all are great features !

  • http://www.broof.de BroOf

    Yes a new version! Some cool new features.

  • http://butai8.com Neal Carroll

    Gonna have to read over this one day. But I am a moorools man that uses jquery sparungly.

  • http://www.mesmerlab.com Jason

    makes me drool… thanks John and Co.!

    and thanks James for this roundup :D

  • Piero

    Great article.

  • http://beerpla.net Artem Russakovskii

    Extremely useful – exactly what we need when new releases come out.

  • Ozory

    Finally !!! Great news.

  • http://www.iconfinder.net martin Leblanc

    Cool. Can’t wait to get started with this new version.

  • http://www.webdevtuts.net Marcell Purham

    Great article. Everything was very well explained

  • http://bcproducties.com/ BCProducties

    Some awesome new features, great article!

  • Max

    thx James for the immediate roundup. how much did John pay envato for that promoting post ;-)

  • http://webneedz.com webneedz

    Perfect new jQuery release, great new features and I’m very happy with the performance boost!
    Thanks for the article.

  • http://andrewburgess.posterous.com Andrew Burgess

    Wow, the jQuery awesomeness never stops; great overview, James!

    I’m curious: what happened to jQuery.require()? In John Resig’s recent talk at Yahoo, I believe he said it would be part of 1.4, but I can’t find anyone mentioning it. Maybe it’s not as big a deal as I thought.

    • http://james.padolsey.com James Padolsey

      Yeh, there was quite a bit of excitement about that, but Resig decided to leave it to a post-1.4 release… He said:

      “As it stands though it’s simply too close to the wire to land this and have it really match expectations. I’m going to push $.require to post-1.4 territory. Thanks again for your tests, jaubourg. Let’s sit down together post-1.4 and really hash out the new ajax code.”

    • http://www.jeffrey-way.com Jeffrey Way

      Hey, Andrew – John wasn’t able to include it…yet.

      • http://www.jeffrey-way.com Jeffrey Way

        He mentioned that he’ll probably first release it as a plugin.

      • http://andrewburgess.posterous.com Andrew Burgess

        Thanks guys!

      • Matthew

        Sweet, ya I was looking forward to this the most.

  • http://www.julien-verkest.fr/ Julien Verkest

    jQuery 1.4 is awesome. I like these fucking great features

  • Chad

    This is amazing. Thanks for pointing these things out!

  • http://bittrack.it Raspo

    I think it’s time to make a donation.

    What about you?

  • http://www.newvibes.com KJ

    Excellent. Can’t wait to get down and dirty with this new version tomorrow.

  • Bernd Matzner

    Great, concise introduction to the new features, thanks for putting this together, and a big thank you to the jQuery team for pushing such useful features to the new release.

  • http://spotdex.com/ David Moreen

    Downloading as i type! :D

  • http://www.vellara.com Nicholas LeBlanc

    Awesome list! Must say that I am the most excited about Passing Attributes to jQuery and Binding Multiple Event Handlers, along with the .has() function. That with the speed and complexity enhancements make this release great. Can’t wait to get cracking and implement some of these new features and functions!

  • http://wpbakery.com Michael

    A lot of interesting stuff thanks!

  • jem

    seems like certain things are starting to become more object oriented in jquery. A lot of the new element creation and event handling is now looking like MooTools and Prototype.

    proxy is also something that should have been built into the framework a long time ago. i suppose jquery in general avoids prototyping native object types, but its certainly simpler in something like mootools where you can apply a .bind() method to any function to affect scope.

    i wonder if we’ll continue to see this sort of a shift in future releases.

  • http://www.boedesign.com Jordan Boesch

    Nice write-up, I always enjoy your stuff James. Another thing that’s worth mentioning is creating custom events with jQuery.event.special. It’s not completely new in 1,4 but there have been some adaptations that have made it a lot better in jQuery 1.4. Here’s a little more about it: http://brandonaaron.net/blog/2009/06/4/jquery-edge-new-special-event-hooks

  • http://enrain.com Jaylin

    In Java, I’m a total noob. What book would you recommend I read on Java?

    • Abderrahmant TJ

      it’s not about Java here !!

    • Mihail Vladov

      Javascript is entirely different from Java.

  • http://blog.webcres.com.br Jefferson

    Very intersting post. I can translate your post to portuguese and publish in my blog ?

    • http://www.jeffrey-way.com Jeffrey Way

      No thank you. :)

      • PureLife Studio

        :)) Don’t be so mean Jeffrey! The guy only wants to help! Just kidding …

        However, translating web design stuff to another language sucks.
        I tried once with an article about design … until I got to ‘goal-oriented design’. God made that expression to stay in English. Translating it to another language is a joke. :)

        Anyway, great article. I just finished the jQuery book (Learning jQuery 1.3 from Packt) and this will be very helpful.

        I also found this cheatsheet: http://www.futurecolors.ru/jquery/

  • Abderrahmant TJ

    Just Awesome is the work that did the jQuery Team !

    Bravo !

  • http://vl.vg/14.01.2010/cross-events/ Regent

    Ooooo! Cool!

  • http://expansive-derivation.ossreleasefeed.com/ Schalk Neethling

    Awesome article James!

  • http://exanimo.com matthew

    Cool stuff. But “most sane event models”? Not so sure I agree with that…

  • http://qzminski.com/ Kamil Kuzminski

    Excellent article!

  • http://www.clintonbeattie.com/ Clinton

    Be good to see some performance stats comparing previous verions and other frameworks. Will be dabbling with the new features soon. Looks good.

  • bob

    Great article. These features of jQuery might allow for easier creation of javascript games, with the detach method.

    Instead of deleting and re-inserting objects into the DOM along with all their data, for example when your character dies and you start a level over, just detach the object, keep it in a variable, and re-insert the object without the added overhead of recreating the object exactly as it was.

    Speed is paramount for games, and among all the speed improvements, I think detach() has the greatest potential to boost the speed and efficiency of javascript for games.

  • http://www.mesmerlab.com Jason

    http://www.ustream.tv/channel/14-days-of-jquery

    Live discussion with John and the guys.

  • http://www.sammybrent.com Sammy

    Awesome stuff – I have a use for 3 of these 15 on active projects straight away!

  • http://mark.chmarny.com Mark

    Good read. Concise and well delivered. How about a follow up on the upgrade to 1.4?

  • JakF

    Hi All,

    Noob question:

    I’m working on receiving a json response from the server using Jquery. According to an article that I saw on funkatron Jquery will (or might??) automatically parse the json using eval. This is bad. Funkatron recommends Crockford’s json2.js to parse json. Jeff Way also recommends this as #23 of his javascript best practices. However you don’t have to use json2.js if your browser natively supports JSON.parse. Yeesh – I’m getting a little confused with all of this.

    Any-hoo my question is: does jquery 1.4 change any of this? Is using jquery to parse json still present potential security risks?

    Thanks in advance for any help/clarification.

    • http://james.padolsey.com James Padolsey

      jQuery 1.4 checks to see if the client supports native JSON parsing. If it does, then it’s used. If it doesn’t then yes, jQuery will use eval (actually, it uses the Function constructor, which is pretty much the same).

      So, if you already have json2.js included in your site then jQuery will use JSON.parse in all browsers.

      • http://encosia.com Dave Ward

        Keep in mind that json2.js uses eval to implement its JSON.parse. It attempts to sanitize the string before the eval, but it’s still eval.

  • http://www.quizzpot.com Crysfel

    I really like the way we can change the context of the listeners (number 6)!!

  • http://bloggerzbible.blogspot.com/ Bloggerzbible

    finally it is released. So excited to know about more plugins

  • http://wp.contempographicdesign.com Chris Robinson

    Looks like some great new features, definitely going to test some out.

  • http://bloggerzbible.blogspot.com/ Bloggerzbible

    And ultimate article too

  • http://sonergonul.com Soner Gönül

    Wow !

    That’s great !

    Thanks !

  • http://vasili.duove.com/ Vasili

    Excellent breakdown of some of the key new features in V1.4. I haven’t really looked at anything besides this post on jQuery 1.4.

    Always love seeing posts from you, James. Hope to see more! :)

  • http://code.google.com/p/jquizme/ Larry Battle

    Kick ass!
    Thanks for the notice, now I can update my plugin, jQuizMe.
    http://code.google.com/p/jquizme/

  • http://www.olympus-tours.com Kevin

    Thanks! I’ve already started trying to implement these in my last project

  • http://brianswebdesign.com Brian Temecula

    Go jQuery! Thanks for the article.