jQuery 1.4 Released: Sneak Peek on New Features and Enhancements

May 30, 2013 · 15 comments

by Lars

jquery 1.4

jQuery 1.4 was just released! First of all a great thanks to the team working hard to make this happen! jQuery was great already and making it better must have been quite an effort. There are several good news for the many jQuery fans as 1.4 is not just a minor maintenance release. You will find that several interesting news and enhancements have been included and that 207 bugs where closed. This article will cover some of the changes you need to be aware of and provide useful information and tools to help you get started with jQuery 1.4. I have created simple demo scripts showing how it works but I have to admit that I’m not a jQuery Guru (just like jQuery a lot) and I had problems creating workable examples for a few features.


ElegantThemes
ThemeForest

Advertisement

jQuery 1.4 has been released on jQuery’s fourth birthday January 14th and the team behind it have launched an awesome on-line event called “14 days of jQuery“. I will recommend that you check it out and participate in the code contests if you have what it takes to collect some of their great prizes! Otherwise just consider keeping an eye on the events…

jQuery 1.4 Released

Get your copy of jQuery now…

In order to start using jQuery 1.4 you need access to the framework. Just like previous versions of jQuery version 1.4 is served from Google’s fast edge cache servers. It is the gzipped version you get this way (compressed using Google Closure Compiler).

You can also get your own jQuery 1.4 here.

With a new version comes a new API documentation that you should take a look at and bookmark. !

Improved Setter Functions

jQuery 1.4 add the .attr() method’s ability to take a function as an argument to all the setter functions: .css(), .attr(), .val(), .html(), .text(), .append(), .prepend(), .before(), .after(), .replaceWith(), .wrap(), .wrapInner(), .offset(), .addClass(), .removeClass(), and .toggleClass(). Example below and demo:

<input type="text" value="click a button" />

<script type="text/javascript">
 $(document).ready(function() {
   $('input:text').val(function() {
     return this.value + ' ' + this.className;
   });
});
</script>

Addtionally, for the following options, the current value of the item is passed into the function as the second argument: .css(), .attr(), .val(), .html(), .text(), .append(), .prepend(), .offset(), .addClass(), .removeClass(), and .toggleClass(). Example below and demo:

<ul>
 <li>Home</li>
 <li>About</li>
 <li>Blog</li>
 <li>Shop</li>
 <li>Contact</li>
</ul>

<script type="text/javascript">
//set width of element based on index value
 $(document).ready(function() {
   $('li').css('width', function(i, value) {
     //have to get rid of 'px' as value returned is fx 1024px
     return value.replace(/px/g,"")/8*i;
   });
});
</script>

Serious performance optimization

Apparently John Resig found areas in the jQuery codebase that where to complex and not as efficient as they could be and he have put significant effort into optimizing performance release 1.4. I found it quite interesting to read how he has been using FireUnit to profile the code. I think I will give it a try soon. As you can see on the graphics below there are rather gigantic efficiency improvements for popular functions like .remove, .html and .empty. Fx. in the specific test referenced number of .html() calls have decreased from 30000 function calls to about 100. Imagine what this mean for performance in complex web applications!jQuery 1.4 Released

  • Performance of .html() has been improved by nearly 3x.
  • Performance of .remove() and .empty() has seen over a 4x speed increase.
  • Performance of .append(), .prepend(), .before(), and .after() has also been improved significantly.

Performance related links

Testing, Performance Analysis, and jQuery 1.4 – In this 1 hours 13 minutes video, John Resig reviews options for testing and performance analysis in JavaScript and previews the significant changes in jQuery 1.4.

Framework Speed Test – Lets you test how jQuery 1.4 performs against MooTools, Prototype and other jQuery versions.

Bind Multiple Events

As of jQuery 1.4 you can bind multiple event handlers simultaneously by passing a map of one or more JavaScript event types and functions to execute for them. Example below and demo:

//This example binds three events in one call.
<div id="example" style="background-color:#FBF9EA; border:1px solid #E2E1D5;">example</div>
<script type="text/javascript">
 $(document).ready(function() {
   $('div#example').bind({
     click: function() {
      alert("clicked!");
     },
     mouseenter: function() {
       $(this).css("background-color", "#fff");
     },
     mouseout: function() {
       $(this).css("background-color", "#FBF9EA");
     }
   });
});
</script>

Check if an Element “Has” Something

The new .has() method in jQuery 1.4 makes it very simple to select elements that has what you’re looking for. In other words the method will select all elements in the current collection that contain at least one element that complies with the passed selector. Example below and demo:

<ul>
 <li>Home</li>
 <li>About</li>
 <li>Blog</li>
 <li>Shop</li>
 <li>Contact</li>
</ul>
<div></div>

<script>
  $("div").append("<span>" + ($("ul").has("li").length ? "Yes! ul has at least one li" : "No! ul has zero li") + "</span>");
</script>

News for working with DOM

In total there are 16 new methods introduced in jQuery 1.4. Three of these are improving the DOM traversal capabilities “nextUntil”, “prevUntil” and “parentsUntil”. Each of these methods will traverse the DOM in a certain direction until the passed selector is satisfied. Let’s assume we need to select an element in some kind of navigation structure – for whatever reason. Example below and demo:

<ul>
 <li>Home</li>
 <li>About</li>
 <li>Blog</li>
 <li>Shop</li>
 <li>Contact</li>
</ul>

<script type="text/javascript">
  $(document).ready(function() {
    // This will select Shop and set color style
    $('ul li:contains(Blog)').nextUntil(':contains(Contact)').css({color: 'green'});
  });
</script>

index()Improvements

In jQuery 1.4 there are new ways to use the .index() method. Basically it is now more intuitive and flexible. In previous versions you could only pass an element as argument to .index() and you’d expect a number to be returned indicating the index of that element within the current collection.

In jQuery 1.4 if no argument is passed to the .index() method, the return value is an integer indicating the position of the first element within the jQuery object relative to its sibling elements. Example below and demo:

<span>Click a div below!</span>
<div>First div</div>
<div>Second div</div>
<div>Third div</div>

<script type="text/javascript">
//On click, returns the index (based zero) of that div in the page.
$("div").click(function () {
 // this is the dom element clicked
 var index = $("div").index(this);
 $("span").text("That was div index #" + index);
});
</script>

Another example demo:

//Returns the index for the element with ID bar in relation to all <li> elements.
<ul>
  <li id="foo">foo</li>
  <li id="bar">bar</li>
  <li id="baz">baz</li>
</ul>
<div></div>

<script>$('div').html('Index: ' +  $('#bar').index('li') );</script>

New Events! focusIn and focusOut

To delegate the focus and blur events you must use focusin and focusout. The focusin and focusout events are sent to an element when it, or any element inside of it, gains focus. This is distinct from the focus event in that they support detecting the focus event on parent elements. Example below and demo:

<p><input type="text" /> <span>focusin event fired</span></p>
<p><input type="password" /> <span>focusin event fired</span></p>

<script>
 $("p").focusin(function() {
 $(this).find("span").css('display','inline').fadeOut(1000);
 });
 $("p").focusout(function() {
 $(this).find("span").css('display','inline').fadeOut(1000);
 });
</script>

New Method: .detach()

jQuery 1.4 introduce a new method called detach() that removes an element from the DOM. The .detach() method is the same as .remove(), except that .detach() keeps all jQuery data associated with the removed elements.

This is appropriate for temporarily removing an element to manipulate and then return. Example below and demo:

<p>p1: Click me to test event handler</p>
<p>p2: Click me to test event handler</p>
<button>Attach/detach paragraphs</button>

<script>
    $("p").click(function(){
      $(this).toggleClass("off");
    });
    var p;
    $("button").click(function(){
      if ( p ) {
        p.appendTo("body");
        p = null;
      } else {
        p = $("p").detach();
      }
    });</script>

Determine the Type of Object

jQuery 1.4 adds two new helper functions that help you determine what type of object you’re dealing with.

isEmptyObject: Check to see if an object is empty (contains no properties).

jQuery.isEmptyObject({}) // true
jQuery.isEmptyObject({ foo: "bar" }) // false

isPlainObject: Check to see if an object is a plain object (created using “{}” or “new Object”).

jQuery.isPlainObject({}) // true
jQuery.isPlainObject("test") // false

New unwrap() method

jQuery introduce a new unwrap method will take the children of a given parent and replace said parent with them. Example lets say you have:

<body>
  <div>
    <p>Lorem Ipsum is simply dummy text</p> <p>Integer nunc mi, ultrices ac elementum bibendum</p>
  </div>
</body>

Then apply this jQuery code

$('div').unwrap();

Should simply produce the following result:

<body>
  <p>Lorem Ipsum is simply dummy text</p> <p>Integer nunc mi, ultrices ac elementum bibendum</p>
</body>

I have tried it here but I can’t really make it work.

Closest() Enhancements

In jQuery 1.4 the .closest() method will accepts an array of selectors. This is quite 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. These enhancements are mainly used internally and aimed at plugin development.

I have tried to create a workable example of this but I could not make it work. Please post a good example in a comment if you have one!

Changes affecting Backwards-Incompatibility

One of the first questions most of you will ask ourselves is probably – “is some of my existing code going to run with jQuery 1.4?”.

The jQuery team have tried hard to maintain backward comparability and state that they are maintaining the signatures of all public functions in jQuery 1.4. Still there is a few things to be aware of as internal changes in behaviour may functionally break your existing code. Also unless your code is really simple and you remember it line by line a few tests may be required before cutting over to the new release….

According the jquery 1.4 release note you need to be aware of the following areas to maintain backwards comparability.

  • .add() no longer plainly concatenates the results together, the results are merged and then sorted in document order.
  • .clone(true) now copies events AND data instead of just events.
  • jQuery.data(elem) no longer returns an id, it returns the element’s object cache instead.
  • jQuery() (with no arguments) no longer converts to jQuery(document).
  • .val(“…”) on an option or a checkbox is no longer ambiguous (it will always select by value now, not by text value). (Commit)
  • jQuery.browser.version now returns engine version.
  • We are now strict about incoming JSON and throw an exception if we get malformed JSON. If you need to be able to evaluate malformed JSON that is valid JavaScript, you can make a text request and use eval() to evaluate the contents.
  • Param serialization now happens in the PHP/Rails style by default. You can use jQuery.ajaxSettings.traditional = true;
    to use traditional parameter serialization. You can also set the behavior on a per-request basis by passing traditional: true to the jQuery.ajax method.
  • The internal jQuery.className removed.
  • jQuery.extend(true, …) No longer extends non-plain-objects or arrays.
  • If an Ajax request is made without specifying a dataType and it is returned as text/javascript, it will be executed. Previously, an explicit dataType was required.
  • Setting an Ajax request’s ifModified now takes ETags into consideration.

The jQuery team have written a plugin that provides backwards compatibility with every potentially-breaking change introduced made in 1.4.

It is simple to use the plugin but you should only do so if you experience any issues:

<script src="http://code.jquery.com/jquery.js"></script>
<script src="http://code.jquery.com/jquery.compat-1.3.js"></script>

jQuery 1.4 Tools and articles

There are not a lot of tools and articles dedicated to jQuery 1.4 yet but you should have access to those that have already arrived. Please drop a comment if you are aware of interesting tools I can add here!

jQuery 1.4 Released: The 15 New Features you Must Know

This post covers the new features and enhancements that you may find beneficial. At this early stage this is probably the best and most comprehensive tutorial on how to use the new features in jQuery 1.4. There are no working code snippets and demos but it’s a good article.

jQuery 1.4 API Cheat Sheet

jQuery 1.4 Released

jsFiddle

jsFiddle now supports jQuery 1.4. It is an online editor that let you test and share your JavaScript, HTML & CSS. jQuery 1.4 Released

jQuery 1.4 iPhone reference app

This is a reference implementation using jQuery 1.4 on iPhone. If you’re coding apps for iPhone this may be interesting for you.

How you can force the Ajax Script Loader to use jQuery 1.4

If you’ve already begun using Microsoft’s new Ajax Script Loader with a CDN-hosted version of jQuery, today’s release of jQuery 1.4 may have left you wondering how to upgrade. Luckily, the script loader is open and extensible enough that it’s possible to change which script versions are used…

yayQuery Podcast

Find out which front-end treats the gang is hoping to find in their stockings, and unwrap a box full of jQuery 1.4 news

14 Days of jQuery – Behind the Scenes –Part 1, Part 2, Part3

<script>$('div').html('Index: ' +  $('#bar').index('li') );</script>

{ 6 comments… read them below or add one }

adem mavili January 22, 2010 at 1:18 am

i found a working example for unwrap function, you can check here:

http://benalman.com/code/test/jquery-unwrap/

Reply

tripwiremag January 22, 2010 at 6:40 am

@adam, thanks a lot for providing this link!

Reply

Elena January 18, 2010 at 6:17 pm

It was interesting to read this article and I hope to read a new article about this subject in your site in the near time.

Reply

tripwiremag January 18, 2010 at 6:32 pm

@Elena, Thanks, This is certainly a subject I will follow up on.

Reply

Kiran January 17, 2010 at 7:59 pm

Look forward to the release and like the sound of performing better than ever before. Keen to read new articles/tutorials based on the release.

Reply

MorayWeb January 17, 2010 at 8:25 am

Handy post for reference, I’ve been looking forward to 1.4 – can’t wait to try out some of the new functions/features!

Reply

Leave a Reply

Your email address will not be published. Required fields are marked *

{ 9 trackbacks }

Previous post:

Next post:


Web Analytics