Fading Coder

One Final Commit for the Last Sprint

Home > Notes > Content

Core jQuery Concepts and Optimization Strategies

Notes 1

Advantages of Using jQuery

jQuery remains a popular library due to its lightweight footprint and concise syntax. It simplifies complex DOM manipulations with powerful selectors and offers robust event handling mechanisms. The library abstracts away browser compatibility issues, supports method chaining for cleaner code, and provides a vast ecosystem of plugins to extend functionality.

Categories of Selectors

jQuery supports a comprehensive range of selectors to target elements:

  • Basic Selectors: Targeting by ID (#id), class (.class), or tag name (element).
  • Hierarchy Selectors: Selecting elements based on their relationship, such as descendants (parent child).
  • Pseudo-class Selectors: Targeting elements by state or index, like :first or :last.
  • Form Selectors: Specifically designed for input elements, such as :input, :checked, or :selected.

Document Ready vs. Window Onload

The primary difference lies in execution timing. The window.onload event fires only after all page assets, including images and external resources, are fully loaded. Conversely, $(document).ready() executes as soon as the DOM hierarchy is fully constructed, allowing for earlier manipulation without waiting for heavy media.

Converting jQuery and DOM Objects

jQuery objects are array-like structures containing DOM elements. To access the raw DOM node, use array indexing (e.g., $(selector)[0]). To wrap a native DOM element back into a jQuery object, pass it to the factory function: $(domElement).

Attribute vs. Property Manipulation

The attr() method is best suited for manipulating custom HTML attributes or the initial state of standard attributes. The prop() method should be used for DOM properties that reflect the current dynamic state, particularly for boolean attributes like checked, disabled, or selected in form elements.

DOM Insertion Techniques

jQuery provides multiple methods for inserting content:

  • Internal Append: append() adds content to the end of the target, while appendTo() reverses the syntax.
  • External Insertion: after() and before() insert content outside the matched elements. insertAfter() and insertBefore() perform similar actions but invert the subject and target.

Essential jQuery Functions

  • find(): Retrieves descendant elements matching the selector.
  • each(): Iterates over a jQuery object, executing a function for each matched element.
  • on(): Attaches event handlers to selected elements.
  • data(): Stores arbitrary data associated with the specified elements.
  • val(): Returns or sets the value attribute of form elements.

Selecting a Specific Radio Button

To programmatically select the second option in a radio group:

const radioButtons = $('input[type="radio"]');
if (radioButtons.length > 1) {
    radioButtons.eq(1).prop('checked', true);
}

Selectors vs. CSS Styles

While jQuery selectors fully support CSS syntax, their purpose differs. CSS selectors are strictly for styling rules. jQuery selectors use the same syntax to locate elements within the DOM to apply behaviors, manipulate attributes, or modify content dynamically.

Style Manipulation

Managing classes is efficient for toggling styles:

  • addClass('className'): Appends a class to the element.
  • removeClass('className'): Removes a class.
  • toggleClass('className'): Adds the class if missing, or removes it if present.

Child vs. Descendant Selectors

A child selector (parent > child) targets only direct descendants. A descendant selector (ancestor descendant) targets any element nested within the ancestor, regardless of the depth of the hierarchy.

Detecting Element Visibility

There are several ways to check if an element is visible:

// Checking computed CSS
const isHidden = $('#element').css('display') === 'none';

// Using jQuery pseudo-selectors
if ($('#element').is(':visible')) {
    console.log('Element is visible');
} else {
    $('#element').show();
}

Difference Between get() and eq()

The get(index) method returns a raw DOM element (or an array of them if no index is provided). The eq(index) method returns a jQuery object containing the element at the specified index, preserving the ability to chain jQuery methods.

Implementing Drag Functionality

A basic drag implementation can be achieved by tracking mouse movements relative to the element's offset:

const $draggable = $('#box');

$draggable.on('mousedown', function(e) {
    const startX = e.pageX - $draggable.offset().left;
    const startY = e.pageY - $draggable.offset().top;

    $(document).on('mousemove.drag', function(ev) {
        $draggable.css({
            left: ev.pageX - startX,
            top: ev.pageY - startY
        });
    });

    $(document).one('mouseup', function() {
        $(document).off('mousemove.drag');
    });
});

Resolving Namespace Conflicts (Multi-Library)

To prevent conflicts with other libraries using the $ alias, use $.noConflict(). This releases control of the $ variable. You can then assign jQuery to a different variable or use an IIFE (Immediately Invoked Function Expression) to scope the $ alias locally.

Array and JSON Conversion

While modern browsers support native JSON methods, you can create utility wrappers in jQuery:

$.fn.arrayToJson = function(arr) {
    return JSON.stringify(arr);
};

$.fn.ToArray = function(str) {
    return JSON.parse(str);
};

const data = ['x', 'y', 'z'];
const Str = $.fn.arrayToJson(data);
const parsedData = $.fn.ToArray(Str);

Object Extension and Deep Copy

The $.extend() method merges the contents of two or more objects.

// Shallow copy (reference copy)
const targetShallow = {};
$.extend(targetShallow, sourceObject);

// Deep copy (recursive clone)
const targetDeep = {};
$.extend(true, targetDeep, sourceObject);

Creating Continuous Animations

To create an infinite animation loop, you can trigger the animation sequence recursively in the callback function:

function animateLoop() {
    $('.mover').animate({ left: '+=200px' }, 1000)
               .animate({ top: '+=200px' }, 1000)
               .animate({ left: '-=200px' }, 1000)
               .animate({ top: '-=200px' }, 1000, function() {
                   animateLoop(); // Restart the loop
               });
}

$('#start').click(animateLoop);

Binding Multiple Events

You can bind a single handler to multiple events by space-separating the event names in the on() method:

$('.input').on('focus blur', function() {
    console.log('Input focused or blurred');
});

Performance Optimization

  • Selector Efficiency: Prefer ID selectors over class selectors, as ID lookups are faster.
  • Context: Provide a context (second argument) to selectors or scope searches starting from an ID to limit the traversal scope.
  • Chaining: Use method chaining to reduce the number of times the DOM is queried.
  • Event Delegation: Use $(parent).on(event, child, handler) for dynamically added elements to improve performance.
  • Caching: Store jQuery selectors in variables if they are used repeatedly.
  • Version Control: Always use the latest stable version of jQuery for bug fixes and performance improvements.

Related Articles

Designing Alertmanager Templates for Prometheus Notifications

How to craft Alertmanager templates to format alert messages, improving clarity and presentation. Alertmanager uses Go’s text/template engine with additional helper functions. Alerting rules referenc...

Skipping Errors in MySQL Asynchronous Replication

When a replica halts because the SQL thread encounters an error, you can resume replication by skipping the problematic event(s). Two common approaches are available. Methods to Skip Errors 1) Skip a...

Spring Boot MyBatis with Two MySQL DataSources Using Druid

Required dependencies application.properties: define two data sources and poooling Java configuration for both data sources MyBatis mappers for each data source Controller endpoints to verify both co...

Leave a Comment

Anonymous

◎Feel free to join the discussion and share your thoughts.