Tuesday, October 11, 2011

Upgrading from jQuery 1.4 to jQuery 1.6

The jQuery team have done a god work in keeping the new versions of the framework backwards compatible. But when we upgraded one of our applications that heavily depends on jQuery we found two breaking changes that affected big parts of the application.

attr() VS prop()

From the documentation:
"The .prop() method gets the property value for only the first element in the matched set. It returns undefined for the value of a property that has not been set, or if the matched set has no elements. To get the value for each element individually, use a looping construct such as jQuery's .each() or .map() method.
The difference between attributes and properties can be important in specific situations. Before jQuery 1.6, the .attr() method sometimes took property values into account when retrieving some attributes, which could cause inconsistent behavior. As of jQuery 1.6, the .prop() method provides a way to explicitly retrieve property values, while .attr() retrieves attributes."
For example, in jQuery 1.4 you could do this

if ($("#radioButton1").attr("checked", "checked")){

if ($("#radioButton1").attr("checked", "")){

when running that code in jQuery 1.4 you could get true or false depending if the checked value wasn't there. That's because if the attr() function doesn't find the checked attribute it returns an empty string. In jQuery 1.6 the attr() function will retrieve the content attribute, which doesn't change when the value is toggled between checked and unchecked, thus always returning true.

The new way of checking if a checbox or radio button is selected is with this code.

if ($("#radioButton1").prop("checked")){


if ($("#radioButton1").is(":checked")){

This is also the best cross-browser way of checking for boolean DOM values.
I'll end with a heads up from the jQuery documentation:
In Internet Explorer prior to version 9, using .prop() to set a DOM element property to anything other than a simple primitive value (number, string, or boolean) can cause memory leaks if the property is not removed (using .removeProp()) before the DOM element is removed from the document. To safely set values on DOM objects without memory leaks, use .data().