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!');
});
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()".
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);
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.
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()".
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.
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!"
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.
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:
- after
- before
- append
- prepend
- addClass
- toggleClass
- removeClass
- wrap
- wrapAll
- wrapInner
- val
- text
- replaceWith
- css
- attr
- html
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!
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.

- Follow us on Twitter, or subscribe to the Nettuts+ RSS Feed for the best web development tutorials on the web.




new jquery , make life even more easy
jQuery.. love it.. :)
wow now i need to learn 1.4 looks like a heavy change was\update was made
last night only I was getting confused with continuous parents and child function calls… and now I found the “until feature”… great job… :-)
“Enjoy jQuery 1.4, the most anticipated, most feature-rich, best performing release of jQuery yet!” Lol, well you’d hope so really.
Great list, thanks for that.
Very nice Update…it grows and is still gettin better and better…. i love jQuery
Great effort on performance. Nice!
Nice, jQuery does indeed rock!
woow jquery rocks….. thanks for this lovely tutorial.
… and jQuery just keeps on moving forward, transforming the way we code on the web …. awesome.
Is the code screwy for anyone else?
May I suggest a better code posting WordPress plugin? http://wordpress.org/extend/plugins/syntaxhighlighter/
(Full disclosure: I wrote it, but in my defense it’s probably the most popular code posting WordPress plugin. ;) )
Regardless, thanks for the guide. :)
Brilliant article. Very well written. Thanks James :)
Performance Comparison: Nice! Love it!
I have only one word to say: MOOTOOLS.
Thank you for your attention.
Wow,
the thing i love the most in v1.4 is the support for “submit” event in live()
Very nice Article to update all the developers. Thanks
I want to learn javascript before i go into jquery…
just one question,james used JQuery instead of $,just to show or new rule that jquery needs to be used instead of $ ?
jeffrey did you forget,you were running something like Javascript from null? i forgot about it,long time no see :)
I was going to ask the exact same question.
I know when you’re using jQuery with another framework you can use something called jQuery.noConflict() that basically allows you to change $ into anything.
Not sure if that’s what you’re asking, hopefully it was :P
Nice Tutorial of updates in the new jQuery 1.4 version
DOM Scripting is a very powerful and appealing way to add interaction to an inanimate website.
yea!!! jQuery rules!! :)
Can’t wait to use the Until
Yeah, jQuery is really awesome. And, most important: Extremly simple to use!
Big thanks to the jQuery Team for this great js framework
I predict that the per-property easing is going to be very useful to many developers. Makes me think of Greensock’s TweenMax for Flash.
awesome. i love jquery.
I’m converting my sites over so far no problems. I really want to commend the jQuery team for that. Looking forward to trying some of these new functions they seem immensely useful.
Great list of key changes! Well written, fast delivered!! Good work, Thx!
Is Adobe actually feeling a threat from libraries like jQuery and new browser capabilities like HTML5 and CSS3? And yes, I have a huge chip on my shoulder that I need to pay so much for their tools simply to teach my stepson how to build Flash apps and games.
nice jquery information . thankyou
Great :) Now I’m hoping for new release of jquery UI…
Hope to see in the future with new jQuery anim. approach!
Helpfull information, THX
Thanks for the Article! Have to get through the new futures in the next couple of days. I’m looking forward to make new things happen on my page. :D
Many new things. I think, I’ll put expect more from my programmers now… ;)
LMFAO! jQuery must really love mustard, because the really love playing katch-up…
Just in case anyone hasn’t been out of their jCave in quite a while, tons of the features in this 1.4 release are features that have been in Mootools/Prototype for YEARS…here are a few that really make me say “Holy guacamole Batman, you JUST figured this out!”
1. Passing Attributes to jQuery(…) – duh, duh, and one more thing, duh.
3. Binding Multiple Event Handlers – see above, and for chr*st sake people you should ALWAYS have been able to pass in multiple props/events/attrs etc via an object in these frameworks, if you couldn’t before they screwed the pooch. Period
6. Controlling a Function’s Context – uh, this actually came from Protoype JS, regardless of this “feature” being in 1.4, you should know that jQuery calls it “.proxy()” because it has always used the now native function context modifying method “.bind()” improperly to set event handlers – so in truth, this is not a feature, it is a work-around for not keeping up to date with javascript, tear ;(
7. Delay an Animation Queue – see Mootools 1.1, circa 2006
8. Check if an Element Has Something – gee, ya think?
Oh, but feel free to continue with the “OMG IE7 created tabbed browsing” party…
Daniel, seriously, you should know better.
jQuery isn’t about being new and cool. It’s about providing a set of features that are useful and intuitive.
You seem sour for some reason, when there is no reason at all. You seem to have forgotten that we’re all on the same team.
Seriously, “LMFAO” — were you really just sitting there, at your desk, laughing your a** off? Really?
I wish people like you were big enough to leave a URL instead of just a name. Ashamed, are you?
What do you mean “big enough” to leave a URL??? You want some personal blog URL, for what reason? Why does that instantly make me ashamed? (In truth, I actually have a reason and it has nothing about being ashamed – I can’t leave my blog or work email because I cannot associate my position with any personal view)
I simply would like other frameworks to get credit for stuff THEY do, and THEY release.
I did a quick search of NetTuts and found:
- 2 posts that covered jQuery releases and 1 for a jQuery UI release
- 0 posts for any release of any kind from Mootools or Prototype – Why is that James?
You didn’t cover Mootools 1.2 – which had a the many of the features of this jQuery release. What about the Mootools Forge? You cover jQuery UI but not the Forge? Something doesn’t smell right here James… The reason I “LMFAO” (maybe that WAS too over the top) is because people actually seem to be clueless about what is available out there already – maybe it is because, in general, the blog outlets are choosing to only cover the releases of jQuery, which makes it more the fault of blog owners and content writers than anyone else, IMHO.
When you are balanced in your coverage people might not feel as much like there is a giant elephant in the room named Favoritism.
“And that’s the Word.”
We’re more than happy to cover Mootools’ next release! Daniel – with respect, you come across as childish. As James put it, we’re all on the same team here. Mootools is a wonderful library as well – one that we do cover from time to time. With that said, jQuery is far more popular, and it’s my job to promote content that will appeal to as wide an audience as possible.
Speaking of which, I have a Mootools tutorial from one of the team members scheduled to be posted tomorrow.
Be happy, Daniel. :)
Sorry, I am really passionate about the subject and get on a tear sometimes. I should have cogently outlined the roots of those features instead if making such inflammatory insinuations.
That said, one of the features of the jQ 1.4 release, the different easing option per attribute, was really kick ass – I hope Mootools takes note on that and implements it! [ and gives the jQ team their credit of course :) ]
I understand. Just remember that Mootools only accounts for about 3% of all JavaScript library users. We must cater to the majority.
Not trying to be combative or argumentative – I think we’ve all had enough of that! :) – but 3% is inaccurate according to a credible source with over 2,328 respondents: http://css-tricks.com/poll-results-what-javascript-library-do-you-use/
I guess the idea of “powerful” is relative to the persons involved in a given discussion. Some folks feel “powerful” means least amount of characters to do something, or the smallest in weight. While those two items are important (and Mootools Core is virtually the same size as jQuery) there is so much more developers seem generally aloof of, such as: reuse, ability to scale, extensibility, modularization, feature… the list goes on.
In one sentence I would sum it up in the following way: Mootools has a bit of a higher learning curve than jQuery, but is a super-set of jQuery not simply an “equally complete” alternative. There is just a ton of stuff that jQuery doesn’t do and it shows.
Ironically, I had to use jQuery this weekend on an application, I had an array of numbers and needed to continually get only unique items from – here is what I found when going to the jQuery docs:
“Remove all duplicate elements from an array of elements. Note that this only works on arrays of DOM elements, not strings or numbers.” – http://docs.jquery.com/Utilities
So I guess this sort of stuff represents the essence of why I get frustrated sometimes when others treat jQuery like this amazing library that is so “powerful”. I mean, discounting the really complex things that it doesn’t even care to provide, even simple things like the one I referenced are just not there.
Not sure what I am expecting of people, perhaps to become fully informed before falling head over heals in love with one solution…but that is probably a utopian idea…i digress.
Nice and clear tutorial, something I would’ve expected from the main jQuery site. Thumbs up!
Great News! thx :D
Why isn’t 1.4 available to download from the official jQuery website http://docs.jquery.com/Downloading_jQuery#Download_jQuery ?
Is this 1.4 version for testing purpose only or is it safe to use in production?
It’s available now on that page.
Many thanks for this quick overview!
Great features!!!
Very well written article James!!! Good job!
i’m using jquery 1.3 it’s awesome, and i just read this article it’s more awesome ….
Very nice, thanks for the update!
I like the changes!! Look forward to implementing my first 1.4 code.
Very good article :)
Great Post! Thanks!
Thanks for this list of helpful features. jQuery is becoming more and more my JavaScript library of choice.
Maybe in some cases it is already over-designed, as with the “xxxUntil()” methods. None the less these methods come in handy.
Really good and helpful
Thanks
I love jQuery, its such a nice bridge between Design and Dev and it looks like this latest version is going to be better still!
I especially like the animation delay and multiple event binding, thanks for the info!
jquery rulz