← back to articles

What’s New in jQuery 3.0 and How to Use It

Save article ToRead Archive Delete · Log out

7 min read · View original · sitepoint.com

This article is part of a web development series from Microsoft. Thank you for supporting the partners who make SitePoint possible.

jQuery, the world’s most popular JavaScript library to date, has been a boon for a lot of us web developers out there. From the time of its initial release in 2006 till today, a lot of us web developers have included this wonderful library in our projects to make our life easier.


Back in July 2015, jQuery announced the first alpha of jQuery 3.0 – a major release after a long time. Let’s take a look at what’s new in jQuery and how you can use it.

show() and hide()

There’s a major change with how these functions will work. And there’s good reason to do so. With the earlier implementation, hide() would set the display:none and show() would clear it up. But this led to some mess. Let’s look at a couple of examples:

  1. If there’s an implementation of display:inline on an element in another stylesheet when the show() method was trying to set display:block, this would start breaking code.
  2. When we’re working with media queries for responsive web design (RWD), we may change the visibility of elements using display or visibility. This may interfere with show() and hide().

In addition to these, there were many other issues which the jQuery team had to fix to get things working. This led to complex implementation and performance issues, and hence, they moved to a simple model.

Hence, if you set display:none and use show(), slideDown(), fadeIn() or similar methods to display that element, it won’t work. The better way to go about it is to use addClass() and removeClass() to control visibility. Or we can call hide() on the elements during the ready() call.

Quick sample:

<!DOCTYPE HTML>
<html>
	<head>
	<style>
		.invisible{
			display: none;
		}
		.visible{
			background-color: deepskyblue;
			display:block;
		}
	</style>
	<script src="jquery-3.0.0-alpha1.js"></script>
	<script>
		$(document).ready(function(){
			$("#div1").addClass("invisible");
			$("#toggle").click(function(){
				$("#div1").removeClass("visible");
				$("#div1").addClass("invisible");
			});
		});
	</script>
	<title>Control Visibility</title>
	</head>
	<body>
		<p>Hello!</p>
		<div id="div1">Can you see this?</div>
		<button id="toggle">Click me</button>
	</body>	
</html>

Control visibility

Control visibility

Nomenclature for .data() Key Names

The jQuery team changed the .data() implementation to closely match the HTML5 dataset specification. If the key in the data-* attribute contains a digit, the digits will no longer participate in the conversion. Consider this example:

With jQuery 2.1.4:

data attribute in jQuery 2.1.4

The console window does not display the object.

With jQuery 3.0.0:

data attribute in jQuery 3.0.0

The key is converted to foo-42-name as digits do not participate in the conversion to camel case now. Hence, we get the output in console. The fiddle is available at http://jsfiddle.net/nWCKt/25/. You can change the jQuery versions to see the changes.

Similarly, if we want to display all the data using data() with no arguments, the number of arguments will change in the two versions of jQuery if any of the key names of data-* attributes had a digit immediately after the hyphen (-), like in the above case.

width() and height() return decimal values

Some browsers return subpixel values for width and height. jQuery now returns decimal values for .width(), .height(), .css(“width”), and .css(“height”) whenever the browser supports it. For users looking for subpixel precision for designing webpages, this may serve as good news.

.load(), .unload(), and .error() methods are removed

These methods which were deprecated earlier, have now been removed from in jQuery 3.0.0 alpha. The recommended way is to use .on() to handle these events. Short example:

HTML:

<img src="space-needle.png" alt="Space Needle" id="spacen">

JavaScript:

Earlier implementation (now defunct)

$( "#spacen" ).load(function() {
  // Handler implementation
});

Recommended implementation:

$( "#spacen" ).on( "load", function() {
	// Handler implementation
});

jQuery Objects are Iterable Now

Iterating over jQuery objects is possible now, using ES2015 for-of. So, you can use things like:

for ( node of $( "<div id=spacen>" ) ) {
	console.log( node.id ); // Returns ‘spacen’
}

(Source here)

jQuery Animations Now Use requestAnimationFrame API at the Backend

All modern browsers now support requestAnimationFrame (status here: http://caniuse.com/#search=requestAnimationFrame). With its popular support, jQuery will use this API when performing animations. Advantages include smoother animations and less CPU-intensive animations (hence, saving battery on mobiles).

Enhancement of .unwrap() Method

.unwrap() method, which lets you remove the parents of the matched elements from the DOM, did not use to accept parameters earlier. This could be an issue if someone wants to unwrap basis a condition set on the parent.

With jQuery 3.0.0 alpha, .unwrap() accepts the jQuery selector parameter to handle this.

jQuery.Deferred Updated to be Promises/A+ Compatible

A promise is an eventual result of an asynchronous operation – it is an object that promises to deliver a result in future. The primary way of interacting with promise is through the then method, which registers callbacks. Using Promise for asynchronous work in JavaScript is becoming increasingly popular these days. Promises/A+ is an open standard for interoperable JavaScript promises. (For more info, check out this link: https://promisesaplus.com/)

From jQuery documentation, the Deferred object is a chainable utility object created by calling the jQuery.Deferred() method. It can register multiple callbacks into callback queues, invoke callback queues, and relay the success or failure state of any synchronous or asynchronous function. In jquery 3.0.0 alpha, the jQuery.Deferred objects are updated to be compatible with Promises/A+ and ES2015 Promises. Hence, there were major changes madeto .then() method.

Better Handling of Error Cases

This version of jQuery has better handling of error cases – incorrect requests which have been ignored till now, throw up errors.

For example: Consider offset, which gets the current coordinates of the first element, in the set of matched elements, relative to the document. If you were trying to find out the offset for a window with earlier versions of jQuery, you’d get the result as {top: 0, left: 0} instead of an error being thrown, since the offset for a window does not make sense. With the 3.0 alpha version, it will now throw up an error.

Another example: $("#") now throws an error rather than returning 0-length collection.

Massive Speedups for Custom Selectors Like :visible

There have been massive performance improvements made when selectors like :visible are used in a document multiple times. Internally, this is done by caching – so the first time the selector is used, the result is the same. But, each call after that gives results way faster, since caching comes into play. Timmy Willison from jQuery reported that it leads to about 17x improvement for the :visible selector!

These were among some of the major updates made. Entire list is available on their official blog: http://blog.jquery.com/2015/07/13/jquery-3-0-and-jquery-compat-3-0-alpha-versions-released/.

Where to Download the Latest Version

There are two releases:

  1. jQuery 3.0, which supports modern browsers : https://code.jquery.com/jquery-3.0.0-alpha1.js
  2. jQuery Compat 3.0, which includes support for IE8 : https://code.jquery.com/jquery-compat-3.0.0-alpha1.js

They are also available on npm:

npm install jquery@3.0.0-alpha1
npm install jquery-compat@3.0.0-alpha1

Feel free to try out this alpha version and give feedback on https://github.com/jquery/jquery. It’s worth a shot!

More Hands-on with Web Development

This article is part of the web development series from Microsoft evangelists and engineers on practical JavaScript learning, open source projects, and interoperability best practices including Microsoft Edge browser and the new EdgeHTML rendering engine.

We encourage you to test across browsers and devices including Microsoft Edge – the default browser for Windows 10 – with free tools on dev.microsoftedge.com:

More in-depth learning from our engineers and evangelists:

Our community open source projects:

More free tools and back-end web dev stuff: