📜 ⬆️ ⬇️

Chapter 3. Animate the jQuery page

Another chapter from the book “jQuery in Action” (by Bear Bibeault and Yehuda Katz). First of all, I apologize to readers for such a large interval between the publication of chapters. But still I did it, which, of course, I am glad. I hope that you, too, will not remain indifferent. So, we continue.

Chapter 3. Animate the jQuery page.


3.1. Manipulating the properties and attributes of objects.


3.1.1. Manipulation with the properties of objects.


The easiest way to check or change the elements of the set we have selected is using the each () command:

$('img').each(function(n){
this.alt=' image['+n+'] id '+this.id;
});


This expression will apply the specified function to each <img> element on the page, in this case the alt attribute will be changed using the sequence number of the element and its id.
')

3.1.2, 3.1.3 Getting and changing attribute values.


As we will see later, many methods in jQuery are used for both reading and writing, depending on the attributes and the number of attributes passed to the method.

So, the attr () method can be used both to get the value of attributes and to set them. If only the attribute name is passed to the method, it will return its value, for example:

$(“#myImage”).attr(“alt”)

so we get the alt for the element with id #myImage.

And so:

$(“#myImage”).attr(“alt”,” picture”)

As you may have guessed, install the same element alt “My picture”.

It is worth noting that instead of a new attribute value, you can pass a function to this method. Example:

$('*').attr('title',function(index) {
return 'I am element '+index+' and my name is ' +
(this.id ? this.id : 'unset');
});


This is a difficult function for us to run through all the elements of the set on the page, changing the title attribute in accordance with the index of the element and its id.

Moreover, the attr () method allows changing several attributes simultaneously:

$('input').attr({value: '', title: 'Please enter a value'});

Thus, we can clear all input values ​​and set their title as “Please enter a value”.

3.1.4 Attribute Removal.


In order to remove an attribute from a DOM element, jQuery has a special method removeAttr (). For example:

$('img').removeAttr('alt');

so we will remove the alt attribute on all selected img elements.

3.2 Working with styles of elements.


3.2.1 Add and remove class names.


The definition of a class is made very simple using the addClass () method, which assigns the class name passed to it to all elements in the set. For example:

$('img').addClass('noBorder');

Class removal is done with the removeClass () command:

$('img'). removeClass ('noBorder');

The following method is quite interesting: toggleClass () assigns a class to an element in a set if this class has not been defined for it, and, conversely, deletes the class from an element in the set if the class has been assigned.

It is very useful to apply such a method in tables, where, let's say, we need to change the shaded lines to white, and the white ones to shaded. This is done like this:

$('tr').toggleClass('striped');

where striped was the class name for the shaded string.

3.2.2 Getting and setting styles.


Working directly with styles gives us great opportunities.

The css () method works similarly to the attr () method, allowing us to set individual CSS properties for an element, pass a name-value pair to the method, or even change several properties, passing new values ​​for them in the object.

Moreover, the method also perfectly handles the functions passed to it as a value for a property. For example, increase the width of elements in the set by 20 pixels:

$('div.expandable').css('width',function(){
return $(this).width() + 20 + “px”;
});


The following example shows the possibility of passing the parameter group method as objects:

$('div.example').css({width: '100px', height: '200px'});

And finally, the css () method allows you to get the value of the property passed to the method. For example, you can find out the width of an element like this:

$('div.examle').css('width');

There are special commands for frequently used properties in jQuery. So, we can find out or change the height and width of objects using special methods height () and width (). Accordingly, if we pass a value to a method, we set this value according to the method that received it, and if we just call the method, we will get the value we need (the transferred value will be set in pixels), that is:

$('div.example').width(500)

will set the block width to 500 pixels. By the way, this is the same as

$('div.example').css(“width”,”500px”)

Now you can find out the width of the block like this:

$('div.example').width()

3.2.3 Some more useful commands for working with styles.


Sometimes it is necessary to check whether an element belongs to a particular class or not. The hasClass () function will help to do this:

$('p:first').hasClass('supriseMe')

If any item in the set belongs to the specified class, the function returns true.

3.3 Setting content of elements.


3.3.1 Replacing HTML or Text.


The simplest command, html (), returns the HTML code of the first matching element, if the parameter was not specified, or sets the HTML fragment passed as a parameter, with the contents of all the selected elements.

Also, it is possible to get only the text content of the elements. For this there is a text () command.

<ul id="theList">
<li>One</li>
<li>Two</li>
<li>Three</li>
<li>Four</li>
</ul>


var text=$('#theList').text();

As a result, the text variable will contain the string “OneTwoThreeFour”.

As with the previous function, we can set the text content for an element, if the test () function has the necessary text as a parameter. Moreover, if in the text there are characters <or> they will be replaced with special characters.

It is worth noting that using these two commands to set the contents of the elements will remove the previous contents, so use these commands carefully.

3.3.2 Moving and copying elements.


To add content to the end of the existing one, use the append () command.

The function adds a string or HTML fragment, passed to it as parameters, to a new or existing DOM element, or to a set of nested jQuery elements. Consider a few examples.

$('p').append('<b>some text</b>');

This expression will append the HTML fragment created from the transferred function of the line to the end of the already existing content of all <p> elements on the page.

A more complex use of this command allows you to assign existing DOM elements as children to other elements. I.e:

$("p.appendToMe").append($("a.appendMe"))

allows you to assign all appendMe class references as child elements of all <p> on the appendToMe country class. In this case, the final position of the assigned elements depends on the number of target elements. If there is one, then the assigned elements will be moved from their original position on the page, if there are several target elements, then the assigned elements will remain in their original place, and their copies will be assigned to the target elements.

To move or copy an element from one place to another, you can also use the appendTo () command, which moves all elements of a nested set to the end of the contents of the target element specified as a function parameter. See an example to see the difference from the previous function:

$(" a.appendMe").appendTo($("p.appendToMe "))

Again, both the selector and the DOM element can act as a target. As in the previous function, if the target element is one, then a move operation will be performed, if there are several targets, then a copy will be made.

The principle of operation of the following commands is similar to the work of append () and appendTo ():
• prepend () and prependTo () - inserts the source element before the target, not after.
• before () and insertBefore () - inserts an element before the target elements, and not before the first descendant.
• after () and insertAfter () - inserts the element after the target elements, and not after the last descendant.

Consider the following example:

$('<p>!</p>').insertAfter('p img');

This expression will create a new paragraph and insert copies of it after each drawing inside the paragraph.

3.3.3 Embedding elements


Another type of DOM manipulation to which we often refer is the embedding of elements (or groups of elements) in some other element. For example, we want to put all the links of a particular class inside a <div>. You can do this with the wrap () command. This method puts the selected set of elements inside the transmitted HTML code or a clone of the transferred element.

For example, to nest every reference of the class of surprise in the <div> class of hello, we do the following:

$(“a.surprise”).wrap(“<div class='hello'></div>”);

If we want to attach each link to a copy of the first <div> on the page:

$(“a.surprise”).wrap($(“div:first”)[0]);

What to do if we need to put all the selected elements not one by one, but together in some kind of common container? The wrapAll () function will help us with this.

Well, when we want to place not every element in the container we need, but only its contents, we use the wrapInner () function.

3.3.4 Deleting items


If we want to clear or remove a set of elements, this is easily done using the remove () command, which removes all the elements of a nested set from the DOM on the page.

It should be borne in mind that, like many other jQuery commands, the result of this command is, again, a set of elements. And even though we removed it from DOM, we can still use it in other functions, for example, the same appendTo () or insertAfter () or other similar functions.

To clear the elements from their contents, you can use the empty () command. It deletes the contents of all the DOM elements in the set.

A common use is remove () and after () for a replace operation. This is done in a similar way:

$('div.elementToReplace').after('<p> </p>').remove();

Since after () returns the original <div> element, we can simply remove it, leaving only the new paragraph <p>.

If you liked the idea, you can modify it and write the following function:

$.fn.replaceWith = function(html) {
return this.after(html).remove();
}


Then we will perform the previous operation as follows:

$('div.elementToReplace').replaceWith('<p> </p>');

And what to do when we want not to move the elements, but only to copy? ..

3.3.5 Element Cloning


For this, jQuery has a clone () command. It creates and returns a copy of the set. All items and descendants are copied. When the true parameter is passed, all handlers are also copied.

Cloning elements is ineffective until we do something with a copy. It all depends on our imagination. Here are a couple of examples:

$('img').clone().appendTo('fieldset .photo');

This expression makes a copy of all the images and places them in all the <fieldset> elements of the class photo.

One more example:

$('ul').clone().insertBefore('#here');

Performs a similar operation. It is worth noting here that all <ul> elements are cloned, including their descendants <li> (if there are such, of course).

And the last example:

$('ul').clone().insertBefore('#here').end().hide();

This expression is similar to the previous operation, but after inserting a copy, the end () command selects the original set, after which it is hidden by the hide () command.

3.4 Operations with form elements


The main action that is performed on forms is working with their data. The val () command returns the contents of the value attribute of the first element in the set. When a form element contains several choices, an array of values ​​for all of these options is returned.

This command, although quite useful, has several limitations. If the first element of the set is not a form element, we get an error message. Also, this command does not distinguish between checked and unchecked items of checkboxes or radio bats.

For the case of radiobathing, you can do the following:

$('[name=radioGroup]:checked').val()

This expression will return the value of a single selected radiobath named radioGroup (or return the value undefined if no radiobath has been selected). This example cannot be applied to checkboxes, since more than one selected value is possible here, and as already mentioned, val () returns the contents of the value attribute of the first element in the set.

When passing a parameter to a command, it will be set as a value for the value of all selected elements of the set. At the same time, there are a number of limitations. For example, you cannot set multiple values ​​for an element with multiple selections.

Another way to use val () is to check the checkboxes and radio boxes or select <select> options. In this case, an array of values ​​is transferred, and if any of them coincides with the value of the element, the element will be selected (checked). For example:

$('input,select').val(['one','two','three']);

This expression checks all <input> and <select> elements to match their values ​​with any of the passed strings: one, two, or three. If the values ​​match, the checkboxes or radio bats will be marked, the select option will be selected.

The next chapter came to an end. Again, I will be glad to healthy criticism. Thank.

Also I remind you that you can always find this and other articles in my blog , you can also go there ;-)

Source: https://habr.com/ru/post/45107/


All Articles