How awesome is jQuery?

  • JQuery was released in 2006 and is by far the longest-lived front-end library. It is also the most widely used library in the world, with 80% of the top 100,000 websites in the world still using jQuery
  • This is jQuery usage data as of March of this year

Why is jQuery so awesome?

Let’s start with the most salient features of jQuery
  • Simple and easy to use

    How easy is it? Here’s an example:

    • Instead of Query, JS event listeners (IE6 compatible) are written like this
        if (button.addEventListener)  
            button.addEventListener('click',fn);
        else if (button.attachEvent) { 
            button.attachEvent('onclick', fn);
        }else {
            button.onclick = fn;
        }
    Copy the code
    • But if you’re using jQuery, all you need to do is write like this
        $(button).on('click', fn)
    Copy the code
    • If you want to get all the elements corresponding to. Nav >. NavItem, jQuery says so
        $('.nav > .navItem')
    Copy the code
    • In IE 6, you have to write like this
        var navItems = document.getElementsByClassName('navItem')
        var result = []
        for(var i = 0; i < navItems.length; i++){
           if(navItems[i].parentNode.className.match(/\bnav\b/){
               result.push(navItems[i])
           }
        }
    Copy the code
  • It solves the DOM API compatibility problem and makes DOM manipulation easier

  • It supports CSS selectors for selecting components

  • Supports batch manipulation of elements in an array, also known as implicit iteration

  • Support chain operations, you can do very complex logic in a single statement

  • There are easy to use plug-in extension mechanisms

  • Deffered’s asynchronous scheme precedes Promise.

Is jQuery obsolete?

  • Few new projects have been developed using jQuery since a few years ago; Even if there is, it is not something worth showing off.
  • JQuery solves many of the front-end technical pain points and has an unprecedented impact on the front end. But as the front end has evolved, jQuery has become obsolete, and there are better alternatives to the pain points it solves for us.
  • JQuery may be out of date, but it’s still a must-have skill for front-end development.

JQuery design Philosophy

  1. JQuery entry function

    • Wait for the PAGE DOM to load before executing JS
    $(document).ready(function() { JQueryCode })
    Copy the code
    • More succinct, equivalent to DOMContentLoaded in native JS
    $(function() { JQueryCode })
    Copy the code
  2. JQuery top-level object $

    • $is another name for JQuery. You can use JQuery instead of $in your code, but $is simpler.

    • $is the top-level object in jQuery, equivalent to the window in native JS, which wraps elements into jQuery objects using $.

  3. JQuery object and DOM object

    • DOM objects: Elements obtained with native JS
    var myDiv = document.querySelector('div');
    Copy the code
    • JQuery object: jQuery is used to obtain objects, his essence is through$The element object is wrapped and stored as a pseudo-array
    $('div');
    Copy the code
    • JQuery objects can only use jQuery methods, whereas DOM objects can only use native JS properties and methods. They are interchangeable

      $(DOM object);

      ② Convert a Query object to a DOM object:

    $('div').get(index); // index is the index number
    / / or
    $('div')[index];
    Copy the code
  4. Select web elements

    • The basic design idea and usage of jQuery is to “select a web element and do something with it”. This is the fundamental feature that sets it apart from other Javascript libraries.
    • Select expressions can be CSS selectors:
        $(document) // Select the entire document object
        $('#myId') // Select the page element with ID myId
        $('div.myClass') // Select the div element whose class is myClass
        $('input[name=first]') // Select the input element whose name attribute is equal to first
    Copy the code
    • It can also be a jquery-specific expression:
        $('a:first') // Select the first a element in the page
        $('tr:odd') // Select the odd rows of the table
        $('#myForm :input') // Select the input element in the form
        $('div:visible') // Select the visible div element
        $('div:gt(2)') // Select all div elements except the first three
        $('div:animated') // Select the div element that is currently animated
    Copy the code
  5. Changing the result set

    • Design idea: jQuery provides a variety of powerful filters to filter the result set, narrow the selection results.
    $('div').has('p'); // Select the div element that contains the p element
          $('div').not('.myClass'); // Select the div element whose class is not equal to myClass
          $('div').filter('.myClass'); // Select the div element whose class equals myClass
          $('div').first(); // Select the first div element
          $('div').eq(5); // Select the sixth div element
    Copy the code
    • Sometimes we need to start from a result set and move to a nearby related element. JQuery also provides a way to move around the DOM tree:
    $('div').next('p'); // Select the first p element after the div element
          $('div').parent(); // Select the parent of the div element
          $('div').closest('form'); // Select the form parent element nearest the div
          $('div').children(); // Select all the children of div
          $('div').siblings(); // Select the sibling element of div
    
    Copy the code
  6. Chain calls

    • This is the most flattering and convenient feature of jQuery. It works because each step of the jQuery operation returns a jQuery object, so different operations can be linked together.
    • JQuery also provides the.end() method so that the result set can take a step back:
        $('div')
           .find('h3')
           .eq(2)
           .html('Hello')
           .end() // Go back to the step where all h3 elements are selected
           .eq(0) // Select the first h3 element
           .html('World'); // Change its content to World
    Copy the code
  7. Style operation

    • The basic way
     /* $(function() {$(' selector ').css(' property ', 'value '); }) * /
        $('.current').css('backgroundColor'.'red');
    Copy the code
    • Implicit iteration
    • JQuery stores the retrieved elements as a pseudo-array and iterates through all matched elements, rather than manually iterating through them. This internal iteration is called implicit iteration.
    • JQuery uses implicit iteration, eliminating the for loop, and using siblings to find siblings but not their own features
            $(element).click(function(){$(this).css('styleCode'.'style');
                    $(this).siblings().css('styleCode'.' ');
            })
    Copy the code
  8. Operations on elements

    • JQuery design idea: use the same function to complete the getter and setter, that is, “valuer” and “assignment” in one. Whether to evaluate or assign depends on the parameters of the function.
    $('h1').html(); // HTML () takes no arguments to fetch the value of h1
    
            $('h1').html('Hello'); // HTML () takes the argument Hello, which assigns h1
    Copy the code
    • Common values and assignment functions are as follows:
    .html() Takes or sets the HTML content.text() Takes or sets the text content.attr() Takes or sets the value of an attribute.width() Takes or sets the width of an element.height() Takes or sets the height of an element.val() Retrieves the value of a form elementCopy the code
    • Note that if the result set contains more than one element, then all elements are assigned; Fetching only the value of the first element (except.text(), which fetches the text content of all elements).

    • Traverse elements

      JQuery implicitly iterates on elements of the same class. If you want to do different operations on elements of the same class, you need to iterate

      The each() method iterates through elements:

        $("div").each(function(index, DOMEle) { jQueryCode })
      Copy the code
    • Index: index number

      DOMEle: Every DOM element, not a jQuery object, must be wrapped with $to use jQuery methods, otherwise only native JS methods can be used.

    • The $.each() method iterates through elements:

        var arr = [1.2.3];
        $.each(arr, function(index, value) {
            jQueryCode
        })
    Copy the code
    • The $.each() method can be used to iterate over any object, and is mainly used to process data. For example, the index object is also an index (index is the key), and the value is the content of the loop (value).

  9. Element operations: move

    • JQuery provides two sets of methods for manipulating the position of elements in a web page. One set of methods is to move the element directly, and the other set of methods is to move other elements so that the target element is where we want it to be.

      Suppose we select a div element and need to move it after the P element.

      The first method is to use.insertafter (), which moves the div element after the p element:

         $('div').insertAfter($('p'));
    Copy the code
    • The second way is to use.after(), which precedes the p element in the div:
         $('p').after($('div'));
    Copy the code
    • On the surface, the effect of the two methods is the same, the only difference seems to be the perspective of operation. But in fact, there is one big difference between them, and that is that they return different elements. The first method returns the div element, and the second method returns the P element. You can choose which method to use based on your needs.

    • There are four pairs of operation methods using this mode:

    InsertAfter () and after () :// Outside the existing element, insert the element from behindThe insertBefore () and before () :// Outside the existing element, insert the element from the frontAppendTo () and append () :// Inside the existing element, insert the element from behindPrependTo () and. The prepend () :// Inside the existing element, insert the element from the front
    Copy the code
  10. Operations on elements: copy, delete, and create

    • In addition to moving elements, jQuery provides several other important ways to manipulate elements. To copy elements, use.clone(). Remove elements using.remove() and.detach(). The difference between the two is that the former does not retain the event of the deleted element, while the latter is retained for use when re-inserting the document.

      Empty the contents of an element (without deleting it) using.empty().

      Creating a new element is as simple as passing it directly into the jQuery constructor:

          $('<p>Hello</p>');
          $('<li class="new">new list item</li>');
          $('ul').append('<li>list item</li>');
    Copy the code
        // Create element:
        var li = $("<li></li>"); // Create a li tag
    Copy the code
        // Add elements:
        $("ul").append(li); // Add the added element at the end of the ul internal element
        $("ul").prepend(li); / / up front
    Copy the code
        var div = $("<div></div>");
        $("div").before(div); // Add the added element before the target element div
        $("div").after(div); // After the target element
    Copy the code
    Remove elements: $("div").remove(); // Remove the specified element div itself
        $("ul").empty(); // Deletes all child nodes of the specified element
        $("ul").html(""); // Empties the contents of the specified element, essentially equivalent to empty
    Copy the code
  11. Size and position operation

    • JQuery size: return values in numbers without units
    Width()/ height() gets the width and height of the element. InnerWidth ()/innerHeight() gets the width and height of the element including the padding. OuterWidth ()/outerHeight() gets the element containing OuterWidth (true)/outerHeight(true) Get the width and height of the elements including the padding, border, and marginCopy the code
    • JQuery location:

    Offset () sets the offset coordinate of the fetch element relative to the document, regardless of the parent

        / / to get:
        $(element).offset();
        $(element).offset().top;
        $(element).offset().left;
        / / set
        $(element).offset({ top: 200.left: 300 });
    Copy the code
    • Position () gets the offset coordinates of the element with positioned parents, or if neither parent is positioned, the document takes precedence. The position() method can only be obtained and cannot be set
        / / to get:
        $(element).position();
        $(element).position().top;
        $(element).positon().left;
    Copy the code

    The scrollTop() and scrollLeft() Settings get the head and left side of the element to be rolled out.

        // Get the wrapped header of the page
        $(document).scrollTop();
        // Set the head of the page to be rolled out
        $(document).scrollTop(100);
    Copy the code
  12. Utility methods

    • In addition to operating on selected elements, jQuery also provides some element independent utility methods. You can use these methods directly without having to select the element.

    • If you understand the inheritance principles of the Javascript language, you can understand the nature of the tool approach. It is a method defined on the jQuery constructor, jquery.method (), so it can be used directly. The methods that operate on elements are those defined on the constructor’s prototype object, jquery.prototype.method (), so you have to generate instances (that is, select elements) to use. If you don’t understand this distinction, it’s ok to think of utility methods as methods that can be used directly, like javascript native functions.

    • The following tools are commonly used:

    $.trim() removes Spaces at both ends of the string. $.each() iterates over an array or object. $.inarray () returns the index position of a value in the array. If the value is not in the array, -1 is returned. $.grep() returns the elements in the array that meet certain criteria. $.extend() merges multiple objects into the first object. $.makeArray() converts an object to an array. $.type() determines the class of objects (function objects, date objects, array objects, re objects, and so on). $.isarray () checks whether a parameter is an array. $.isemptyObject () determines whether an object is empty (without any attributes). $.isfunction () checks whether an argument is a function. $.isplainObject () determines whether a parameter is an Object created with "{}" or "new Object". $.support() Checks whether the browser supports a feature.Copy the code
  13. Event operations

    • JQuery design idea: bind events directly to web elements.
    $('p').click(function(){
               alert('Hello');
          });
    Copy the code
    • Currently, jQuery supports the following events:
    .blur() Form elements lose focus. .change() the value of the form element changes.click() mouse click.dblclick() mouse double-click.focus() The form element gets focus.focusin() child gets focus.focusout() child loses focus.hover() Specify handlers for both mouseEnter and mouseleave events. Keydown () presses the keyboard (long button, returns only one event). Keypress () presses the keyboard (long button, returns only one event). Mousedown () press the mouse. Mouseenter () mouse in (entering child element does not trigger). Mouseleave () mouse away (leaving child element does not trigger). .mousemove() mouse moves inside the element.mouseout() mouse leaves (leaving the child element also triggers).mouseover() mouse enters (entering the child element also triggers).mouseup() release the mouse.ready() DOM loads complete.resize () The size of the browser window changes. Scroll () The position of the scroll bar changes. Select () Users select content in the text boxCopy the code
    • All of these events are handy ways to use.bind() in jQuery. Using.bind() gives you more flexibility in controlling events, such as binding multiple events to the same function:
        $('input').bind(
           'click change'.// Bind both the click and change events
           function() {
             alert('Hello'); });Copy the code
    • Sometimes, you only want the event to run once, using the.one() method.
    $("p").one("click".function() {
               alert("Hello"); // Only run once, subsequent clicks will not run
          });
    Copy the code
    • .unbind() is used to unbind events.
    $('p').unbind('click');
    Copy the code
    • On binding event syntax:
       element.on(events, [selector], fn);
       /* events: Event type, one or more space-delimited event strings, such as "click", "mouseEnter" selector: child element selector of the event binding element fn: callback function */
    Copy the code
      // The event result is inconsistent
      $(".demo").on({
          mouseenter: function(){$(this).css("color"."red");	
          },
          click: function() {$(this).css("background"."skyblue"); }})// The event results are consistent
      $(".demo").on("mouseenter mouseout".function() {$(this).toggleClass("csstyle");
      })
    Copy the code
    • The ON binding event implements event delegation
       $("ul").on("mouseover"."li".function() { JSCode })
    Copy the code
    • The ON binding event implements binding events to future dynamically created elements
       $("ol").on("click"."li".function(){ alert("Hello"); })
       var li = $("<li></li>");
       $("ol").append(li);
    Copy the code
    • The off() method unbinds event handlers that are bound by on()
       $("div").on({
           mouseenter: function() { alert("Mouse pass event")},click: function() { alert("Mouse click event")}}); $("div").off(); // Unbind all of them
       $("div").off("click"); // Specify event untying
    Copy the code
    • JQuery automatic event trigger
       // element. Event ();
       $("div").click();
    Copy the code
    • The trigger () method:
       $("div").trigger("click");
    Copy the code
    • TriggerHandler () method: This method does not trigger the element’s default behavior
       $("div").triggerHandler("click");
    Copy the code
    • JQuery event object properties and methods
    When the event. PageX event occurs, the horizontal distance between the mouse and the upper left corner of the page Event. type Type of the event (such as click) Event. which Which key is pressed Event. data Binds data to the event object, Event.target event.preventDefault() prevents the event's default behavior (such as clicking on a link will automatically open a new page). Event.stoppropagation () stops the event bubblers to the upper elementCopy the code
    • In event handlers, we can use the this keyword to return the DOM element for which the event was intended:
    $('a').click(function(e) {
               if ($(this).attr('href').match('evil')) { // If confirmed as harmful link
                   e.preventDefault(); // prevents opening
                   $(this).addClass('evil'); // add the harmful class}});Copy the code
  14. Special effects

    • Finally, jQuery allows objects to render certain special effects.
    .fadein () fades in.fadeout () fades out.fadeto () adjusts transparency.hide() hides elements.show() shows elements.slidedown () scrolls down.slideup () curls up.slidetoggle () Unfold or roll up an element in turn. Toggle () displays or hides an element in turnCopy the code
    • The default execution time for all effects except.show() and.hide() is 400ms (milliseconds), but you can change this setting.
    $('h1').fadeIn(300); // Fades in 300 milliseconds
        $('h1').fadeOut('slow'); // Slowly fade out
    Copy the code
    • After the effects are over, you can specify a function to be executed.
        $('p').fadeOut(300.function() {$(this).remove(); });
    Copy the code
    • More complex effects can be customized using.animate().
    $('div').animate({
              left : "50 + =".// Keep moving to the right
              opacity : 0.25 // Specify transparency
            }, 300.// The duration
            function() {
                alert('done! '); 
            }); // The callback function
    Copy the code
    • .stop() and.delay() are used to stop or delay the effect. $.fx.off If set to true, turns off all web effects

Excerpts from:

Personal homepage of Fang Yinghang

Design idea of jQuery – Ruan Yifeng