Chapter 3. Revitalizing a jQuery Page

    The next chapter from the book "jQuery in Action" (authors Bear Bibeault and Yehuda Katz). First of all, I apologize to the readers for such a large gap between the publication of chapters. But still I did it, which, of course, I’m glad. I hope that you too will not remain indifferent. So, we are continuing.

    Chapter 3. Animating a jQuery page.


    3.1. Manipulation of properties and attributes of objects.


    3.1.1. Manipulating with the properties of objects.


    The simplest way to check or change the elements of the set we have chosen is for us using the each () command: This expression will apply the specified function to each element on the page, and the alt attribute will be changed using the element serial number and its id.

    $(‘img’).each(function(n){
    this.alt=’Это image[’+n+’] с id равным ‘+this.id;
    });




    3.1.2, 3.1.3 Getting and changing the value of attributes.


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

    So, the attr () method can be used both to obtain 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”)

    this way we get alt for the element with id #myImage.

    And so:

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

    as you probably guessed, set the same element alt “My picture”.

    It should be noted that instead of a new attribute value, you can pass a function to this method. Example: this function, which is still difficult for us, runs 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.

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




    Moreover, the attr () method allows you to change several attributes at the same time:

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

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

    3.1.4 Removing Attributes.


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

    $(‘img’).removeAttr(‘alt’);

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

    3.2 Work with styles of elements.


    3.2.1 Adding and removing class names.


    Class definition is 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’);

    Removing a class is done with the removeClass () command:

    $(‘img’). removeClass (‘noBorder’);

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

    It is very useful to apply this method in tables, where, for example, we need to change the filled lines to white and the white ones to filled. This is done like this:

    $(‘tr’).toggleClass(‘striped’);

    where striped was the name of the class for the filled line.

    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, passing a name / value pair to the method, or even changing several properties, passing new values ​​to them in the object.

    Moreover, the method also perfectly handles the functions passed to it as the value for the property. For example, increase the width of the elements in the set by 20 pixels: The following example shows the possibility of passing a group of parameters to the method as objects: 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.expandable’).css(‘width’,function(){
    return $(this).width() + 20 + “px”;
    });




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



    $(‘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 the 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 simply call the method, we get the value we need (the transferred value will be set in pixels), that is: it will

    $(‘div.example’).width(500)

    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 element in the set belongs to the specified class, the function will return true.

    3.3 Setting the content of elements.


    3.3.1 Replacing HTML or text.


    The simplest command, html (), returns the HTML code of the first corresponding element if the parameter has not been set, or sets the HTML fragment passed as the parameter with the contents of all selected elements.

    Also, it is possible to get only the text content of the elements. There is a text () command for this. As a result, the text variable will contain the string “OneTwoThreeFour”. As with the previous function, we can set the text content for the element, if the test () function is the required text as a parameter. Moreover, if the text contains the characters <or> they will be replaced by special characters. It is worth noting that using these two commands to set the content of elements will delete the previous content, so use these commands carefully.


    • One

    • Two

    • Three

    • Four



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







    3.3.2 Moving and copying items.


    To append content to the end of an 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. Let's look at a few examples. This expression appends the HTML snippet created from the passed function string to the end of the existing content of all elements

    $('p').append('some text');

    On the page.

    A more comprehensive use of this command allows you to designate existing DOM elements as children of other elements. That is: it

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

    allows you to designate all the links of the appendMe class as children of all

    on the page class appendToMe. 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, but 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 the nested set to the end of the contents of the target element specified as a function parameter. We look at an example to see a difference from the previous function:

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

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

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

    Consider the following example:

    $(‘

    Привет!

    ’).insertAfter(‘p img’);

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

    3.3.3 Nesting Elements


    Another type of DOM manipulation that we often refer to is the embedding of elements (or groups of elements) into some other element. For example, we would like to put all links of a certain class inside
    . This can be done using the wrap () command. This method embeds the selected set of elements inside the transmitted HTML code or a clone of the transferred element.

    For example, to nest each link of the class surprise in
    hello class do the following: If we want to embed each link in a copy of the first element

    $(“a.surprise”).wrap(“
    ”);


    on page:

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

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

    Well, when we want to put 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 clean or remove a set of elements, this is easily done using the remove () command, which removes all elements of the 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 the DOM, we can still use it further in other functions, for example, the same appendTo () or insertAfter () or other similar ones.

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

    It is common to use remove () and after () for a replace operation. This is done in a similar way: Since after () returns the original element

    $(‘div.elementToReplace’).after(‘

    Я заменяю блок

    ’).remove();


    , we can simply remove it, leaving only a new paragraph

    .

    If you liked the idea, you can refine it and write the following function: Then we will perform the previous operation as follows:

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




    $(‘div.elementToReplace’).replaceWith(‘

    Я заменяю блок

    ’);

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

    3.3.5 Cloning Elements


    To do this, jQuery has a clone () command. She creates and returns a copy of the set. All elements and descendants are copied. With the passed parameter true, all handlers are also copied.

    Cloning elements is inefficient until we do something with the 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 images and puts them in all elements
    class photo.

    Another example:

    $(‘ul’).clone().insertBefore(‘#here’);

    Performs a similar operation. It is worth noting here that all elements are cloned.
      including their descendants
    • (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 source set, after which it is hidden with the hide () command.

      3.4 Operations with form elements


      The main action that is performed with 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 multiple choices, an array of values ​​from all of these choices is returned.

      This command, although quite useful, has a number of limitations. If the first element of the set is not a form element, we will receive an error message. Also, this command does not distinguish between marked and unchecked checkbox or radio baton elements.

      For the case of the radio baton, you can do the following:

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

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

      When passing a parameter to the command, it will be set as the value for the value of all selected elements of the set. In this case, again, there are a number of limitations. For example, you cannot set multiple values ​​for an item with multiple selections.

      Another direction of using val () is to set checkbox and radio baton flags or select options and

    Also popular now: