
jQuery 1.4: 15 new features
- Transfer
On January 14, jQuery 1.4 was born. This release contains many new features and improvements. This article discusses the ones you might find most useful.
Before version 1.4, jQuery supported adding attributes to collection elements using the convenient attr method , which took either the attribute name and its value, or an object that defines several attributes at once as parameters. JQuery 1.4 introduced the ability to pass attributes as the second argument when creating an element. Let's say you need to create a hyperlink with several attributes. Using version 1.4, this is done in this way:
You probably noticed the text attribute and you might have been surprised at what it does here, because links do not have such an attribute! The fact is that jQuery 1.4 uses its own methods to process them. Thus, meeting the text attribute , jQuery calls the .text () function and passes the value “Go to Google!”.
Another great example:
The id attribute is treated as a regular attribute, and css and click as calls to the corresponding methods. In previous versions of jQuery, you would write this:
Three new methods have appeared in the arsenal of DOM traversal: “nextUntil”, “prevUntil” and “parentsUntil”. Each of these methods will bypass the DOM in the given direction until the condition of the passed selector is met. So, let's say you have a list of fruits:
You need to select all the items after "Apple" and stop at "Strawberry". It looks very simple:
Instead of using a chain of events, you can bind multiple events in one call at once. For example, like this:
This also works with the .one () method .
Now, instead of defining one function for one type of animation, you can define different functions for each animated property. jQuery includes two types of animation: rocking (default) and ramp. Others you need to download separately .
To specify an animation function for each property, you just need to define an array, the first value of each element is the animated property, and the second function used:
Try-on.
You can also use the specialEasing object , i.e. a record like this:
JQuery 1.4 introduces support for submit , change , focus , and blur event handlers . JQuery uses the .live () method to add event handlers. This is useful when you add handlers for several elements at once, as well as when adding new ones.
Note that you need to use the names 'focusin' and 'focusout' to use the focus and blur events!
jQuery 1.4 provides a new “proxy” function in the jQuery namespace. This function takes two arguments: "scope" and the name of the method. Let's look at an example.
Below, an “app” object is created with two properties: “clickHandler” and “config”.
The ".clickHandler ()" method will have an "app" execution context, this implies that this refers to it. This works as expected:
Let's try to cling to the event:
When you click on the link, nothing will happen. Because jQuery will, by default, set the desired element (in our case, the link) for the handler context, that is, this in this example is a hyperlink. But we do not want this! We want this in this case to mean the “app” object. In jQuery 1.4, this can be achieved very simply:
Now clicking on the link will lead to the expected result.
The proxy function will return a “wrapped” version of your function, and also set the object you specify for “this”. This is useful in such cases when you need to pass a function as a parameter to another jQuery method or to some plugin.
You can now add a pause before processing the animation event queue. In fact, this works with any event queue, but this feature is most in demand precisely when working with animation, that is, with the 'fx' queue. This will save you the confusion of calling setTimeout and passing methods. It looks like this:
If you want to use the method for a queue other than the effects queue (used by default), then you need to pass its name as the second parameter to the function.
jQuery 1.4 makes it easy to check for an element in another. This is equivalent to the : has () filter in the selector. This method returns all elements that contain at least one element corresponding to the passed selector.
In this case, the result will be a collection of div elements that contain the ul element . In this situation, of course, it is more convenient to use the ( : has () ) selector , but the method is useful in cases when you need to filter the collection dynamically.
jQuery 1.4 also provides a “contains” function. This is a low-level function that takes two DOM elements as arguments and returns a logical result indicating whether the second element is contained in the first. For instance:
We all know about the .wrap () method . In jQuery 1.4, the .unwrap () function has appeared , which acts in the exact opposite. For example, we have such a structure:
Calling this code:
... will return us the following structure:
In other words, the method removes the parent of any element.
The new .detach () method will allow you to remove elements from the document, just as the .remove () method does . The key difference is that the new method does not remove information about these elements from jQuery. This implies that both the data added by the .data () method and any event handler added through the jQuery event system will remain active.
This can be useful in cases when you delete an item, but know that you may need it later. His events and data will be relevant in this case.
jQuery 1.4 allows you to use the .index () method in two new ways. Previously, you could pass an element as a parameter, and as a result, get the index of this element in the current collection.
If no arguments are passed to the method, then it returns the index of the element in the collection in which it is located. For instance:
When you click on a list item, a message appears with its index. This is done like this:
jQuery 1.4 also allows you to specify the selector as an argument to the .index () function , which allows you to find out the index in the collection from the processing of the selector.
The return value is of type integer, and the result will be -1 if the item is not found in the collection.
Most document model management methods can now take a function as an argument. This function will be called for each item in the collection, which is defined using the desired method.
The following functions have such an opportunity:
In this function, the current element is this , and its index is passed as an argument.
Also, with some functions you can use the second argument. If you call the so-called installation method (for example .html () or .attr ('href') ), the second argument will be the value. For instance:
As you can see, the .css () and .attr () methods can be passed the second argument to the function, and the first property you want to change:
jQuery 1.4 contains two new helper functions that help you determine the type of target.
Firstly, the isEmptyObject function . This function returns a result of type boolean, and shows whether the passed object is empty (without properties directly or indirectly). Secondly, this isPlainObject function , which shows whether the passed object is a javaScript object created either through '{}' or through 'new Object ()'.
The .closest () method can now take an array of selectors as a parameter. This is very useful when you want to select more than one item with specific characteristics.
In addition, an execution context may be passed as the second argument. That is, you can control how far the desired item will be searched. Both of these enhancements are rarely used in practice, but they have had an amazing effect on jQuery development.
You should use these events when working with focus and blur . These events will allow you to perform any action when an element gains or loses focus.
Note that both of these events are not passed on (bubble effect). This means that the item below or the parent will not receive this event.
Initially, the article was translated for a blog , but since I had the opportunity to publish on a hub (thanks deerua ).
1. Passing jQuery attributes (...)
Before version 1.4, jQuery supported adding attributes to collection elements using the convenient attr method , which took either the attribute name and its value, or an object that defines several attributes at once as parameters. JQuery 1.4 introduced the ability to pass attributes as the second argument when creating an element. Let's say you need to create a hyperlink with several attributes. Using version 1.4, this is done in this way:
jQuery (' ', { id: 'foo', href: 'http://google.com', title: 'Become a Googler', rel: 'external', text: 'Go to Google!' });
You probably noticed the text attribute and you might have been surprised at what it does here, because links do not have such an attribute! The fact is that jQuery 1.4 uses its own methods to process them. Thus, meeting the text attribute , jQuery calls the .text () function and passes the value “Go to Google!”.
Another great example:
jQuery ('', { id: 'foo', css: { fontWeight: 700, color: 'green' }, click: function () { alert ('Foo has been clicked!'); } });
The id attribute is treated as a regular attribute, and css and click as calls to the corresponding methods. In previous versions of jQuery, you would write this:
jQuery ('') .attr ('id', 'foo') .css ({ fontWeight: 700, color: 'green' }) .click (function () { alert ('Foo has been clicked!'); });
2. “until” to everything!
Three new methods have appeared in the arsenal of DOM traversal: “nextUntil”, “prevUntil” and “parentsUntil”. Each of these methods will bypass the DOM in the given direction until the condition of the passed selector is met. So, let's say you have a list of fruits:
- Apple
- Banana
- Grape
- Strawberry
- Pear
- Peach
You need to select all the items after "Apple" and stop at "Strawberry". It looks very simple:
jQuery ('ul li: contains (Apple)'). nextUntil (': contains (Pear)');
3. Multibinding event handlers
Instead of using a chain of events, you can bind multiple events in one call at once. For example, like this:
jQuery ('# foo) .bind ({ click: function () { // do something }, mouseover: function () { // do something }, mouseout: function () { // do something } })
This also works with the .one () method .
4. New in animation
Now, instead of defining one function for one type of animation, you can define different functions for each animated property. jQuery includes two types of animation: rocking (default) and ramp. Others you need to download separately .
To specify an animation function for each property, you just need to define an array, the first value of each element is the animated property, and the second function used:
jQuery ('# foo'). animate ({ left: 500, top: [500, 'easeOutBounce'] }, 2000);
Try-on.
You can also use the specialEasing object , i.e. a record like this:
jQuery ('# foo'). animate ({ left: 500, top: 500 }, { duration: 2000, specialEasing: { top: 'easeOutBounce' } });
5. New events for the live method.
JQuery 1.4 introduces support for submit , change , focus , and blur event handlers . JQuery uses the .live () method to add event handlers. This is useful when you add handlers for several elements at once, as well as when adding new ones.
Note that you need to use the names 'focusin' and 'focusout' to use the focus and blur events!
jQuery ('input'). live ('focusin', function () { // do something with this });
6. Controlling the context of functions.
jQuery 1.4 provides a new “proxy” function in the jQuery namespace. This function takes two arguments: "scope" and the name of the method. Let's look at an example.
Below, an “app” object is created with two properties: “clickHandler” and “config”.
var app = { config: { clickMessage: 'Hi!' }, clickHandler: function () { alert (this.config.clickMessage); } };
The ".clickHandler ()" method will have an "app" execution context, this implies that this refers to it. This works as expected:
app.clickHandler (); // "Hi!"
Let's try to cling to the event:
jQuery ('a'). bind ('click', app.clickHandler);
When you click on the link, nothing will happen. Because jQuery will, by default, set the desired element (in our case, the link) for the handler context, that is, this in this example is a hyperlink. But we do not want this! We want this in this case to mean the “app” object. In jQuery 1.4, this can be achieved very simply:
jQuery ('a'). bind ( 'click', jQuery.proxy (app, 'clickHandler') );
Now clicking on the link will lead to the expected result.
The proxy function will return a “wrapped” version of your function, and also set the object you specify for “this”. This is useful in such cases when you need to pass a function as a parameter to another jQuery method or to some plugin.
7. Pause before performing the animation.
You can now add a pause before processing the animation event queue. In fact, this works with any event queue, but this feature is most in demand precisely when working with animation, that is, with the 'fx' queue. This will save you the confusion of calling setTimeout and passing methods. It looks like this:
jQuery ('# foo') .slideDown () // animation times .delay (200) // pause .fadeIn (); // animation two
If you want to use the method for a queue other than the effects queue (used by default), then you need to pass its name as the second parameter to the function.
8. .has () function
jQuery 1.4 makes it easy to check for an element in another. This is equivalent to the : has () filter in the selector. This method returns all elements that contain at least one element corresponding to the passed selector.
jQuery ('div'). has ('ul');
In this case, the result will be a collection of div elements that contain the ul element . In this situation, of course, it is more convenient to use the ( : has () ) selector , but the method is useful in cases when you need to filter the collection dynamically.
jQuery 1.4 also provides a “contains” function. This is a low-level function that takes two DOM elements as arguments and returns a logical result indicating whether the second element is contained in the first. For instance:
jQuery.contains (document.documentElement, document.body); // Result true - is inside
9. Unwrap!
We all know about the .wrap () method . In jQuery 1.4, the .unwrap () function has appeared , which acts in the exact opposite. For example, we have such a structure:
Foo
Calling this code:
jQuery ('p'). unwrap ();
... will return us the following structure:
Foo
In other words, the method removes the parent of any element.
10. Deleting items without deleting data
The new .detach () method will allow you to remove elements from the document, just as the .remove () method does . The key difference is that the new method does not remove information about these elements from jQuery. This implies that both the data added by the .data () method and any event handler added through the jQuery event system will remain active.
This can be useful in cases when you delete an item, but know that you may need it later. His events and data will be relevant in this case.
var foo = jQuery ('# foo'); // important handler foo.click (function () { alert ('Foo!'); }); foo.detach (); // delete the object from the DOM // ... a lot of code foo.appendTo ('body'); // add an object foo.click (); // "Foo!"
11. Improvements to index (...)
jQuery 1.4 allows you to use the .index () method in two new ways. Previously, you could pass an element as a parameter, and as a result, get the index of this element in the current collection.
If no arguments are passed to the method, then it returns the index of the element in the collection in which it is located. For instance:
- Apple
- Banana
- Grape
- Strawberry
- Pear
- Peach
When you click on a list item, a message appears with its index. This is done like this:
jQuery ('li'). click (function () { alert (jQuery (this) .index ()); });
jQuery 1.4 also allows you to specify the selector as an argument to the .index () function , which allows you to find out the index in the collection from the processing of the selector.
The return value is of type integer, and the result will be -1 if the item is not found in the collection.
12. DOM control methods that take functions as arguments.
Most document model management methods can now take a function as an argument. This function will be called for each item in the collection, which is defined using the desired method.
The following functions have such an opportunity:
- after
- before
- append
- prepend
- addClass
- toggleClass
- removeClass
- wrap
- wrapAll
- wrapInner
- val
- text
- replaceWith
- css
- attr
- html
In this function, the current element is this , and its index is passed as an argument.
jQuery ('li'). html (function (i) { return 'Index of the current element:' + i; });
Also, with some functions you can use the second argument. If you call the so-called installation method (for example .html () or .attr ('href') ), the second argument will be the value. For instance:
jQuery ('a'). attr ('href', function (i, currentHref) { return currentHref + '? foo = bar'; });
As you can see, the .css () and .attr () methods can be passed the second argument to the function, and the first property you want to change:
jQuery ('li'). css ('color', function (i, currentCssColor) { return i% 2? 'red': 'blue'; });
13. Determining the type of object
jQuery 1.4 contains two new helper functions that help you determine the type of target.
Firstly, the isEmptyObject function . This function returns a result of type boolean, and shows whether the passed object is empty (without properties directly or indirectly). Secondly, this isPlainObject function , which shows whether the passed object is a javaScript object created either through '{}' or through 'new Object ()'.
jQuery.isEmptyObject ({}); // true jQuery.isEmptyObject ({foo: 1}); // false jQuery.isPlainObject ({}); // true jQuery.isPlainObject (window); // false jQuery.isPlainObject (jQuery ()); // false
14. Improvements to the closest (...) method
The .closest () method can now take an array of selectors as a parameter. This is very useful when you want to select more than one item with specific characteristics.
In addition, an execution context may be passed as the second argument. That is, you can control how far the desired item will be searched. Both of these enhancements are rarely used in practice, but they have had an amazing effect on jQuery development.
15. New events 'focusin' and 'focusout'
You should use these events when working with focus and blur . These events will allow you to perform any action when an element gains or loses focus.
jQuery ('form') .focusin (function () { jQuery (this) .addClass ('focused'); }); .focusout (function () { jQuery (this) .removeClass ('focused'); });
Note that both of these events are not passed on (bubble effect). This means that the item below or the parent will not receive this event.
Initially, the article was translated for a blog , but since I had the opportunity to publish on a hub (thanks deerua ).