jQuery Custom Utility (jquery_custom.js) 🌟

A lightweight DOM helper inspired by jQuery. It provides a global $ function returning an ElementCollection—an array-like wrapper over DOM elements—with chainable utility methods. This file replaces dependency on jQuery for simple UI interactions and form validation.


Global $ Function

Creates an ElementCollection from:

  • A selector string (queries document.querySelectorAll).
  • A single element or array of elements.
function $(param) {
  if (typeof param === "string" || param instanceof String) {
    return new ElementCollection(...document.querySelectorAll(param));
  } else {
    return new ElementCollection(param);
  }
}

Returns: ElementCollection
Usage:

// Select by CSS selector
$(".btn").fadeIn(200);

// Wrap an existing element
$(document.body).on("click", () => console.log("clicked"));

ElementCollection Class 🔧

Extends Array to hold DOM elements and adds chainable methods.

class ElementCollection extends Array { … }

Supported Methods

Method Purpose Returns
ready(cb) Calls cb when any element is loaded or DOMContentLoaded this
on(...) Attaches event listeners, with optional delegation this
fadeOut(ms) Smoothly fades elements out then sets display: none this
fadeIn(ms) Smoothly fades elements in (sets display: block) this
delay(ms) Pauses the chain for ms milliseconds Promise<ElementCollection>
validate() Attaches form validation on submit this

1. ready(cb) ⏳

Executes a callback when an element is already “ready” (i.e., not loading) or on DOMContentLoaded.

ready(callback: Function): this
  • Checks readyState of any element.
  • If loaded, invokes callback immediately.
  • Otherwise, binds to DOMContentLoaded.

Example:

$(document).ready(() => {
  console.log("DOM is ready!");
});

2. on(event, selectorOrHandler, [handler]) 🎯

Attaches event listeners to each element in the collection.

Signatures:

  1. Direct listener
    on(eventType: string, handler: Function): this
    
  2. Delegate listener
    on(eventType: string, selector: string, handler: Function): this
    

Behavior:

  • Direct: Adds handler for eventType.
  • Delegated: On event, checks event.target.matches(selector) before invoking handler.

Examples:

// Simple click
$(".btn-submit").on("click", e => alert("Submitted!"));

// Delegate: clicks on any `.remove-btn` inside `.list`
$(".list").on("click", ".remove-btn", e => e.target.closest("li").remove());

3. fadeOut(duration = 400) ⚡

Fades elements out over duration ms, then hides them.

fadeOut(duration?: number): this
  • Sets opacity from 1 → 0 with CSS transition.
  • On transitionend, applies display: none.

Example:

$(".alert").fadeOut(600);

4. fadeIn(duration = 400) ✨

Fades elements in over duration ms.

fadeIn(duration?: number): this
  • Sets display: block and transitions opacity 0 → 1.

Example:

$("#modal").fadeIn(300);

5. delay(milliseconds) ⏱️

Inserts a pause in a chain of operations.

delay(ms: number): Promise<ElementCollection>
  • Returns a Promise resolving to the same ElementCollection after ms.

Example:

$(".box")
  .fadeOut(200)
  .delay(500)
  .fadeIn(200);

6. validate(options) 📝

Provides form validation on <form> submit, using a rules/messages pattern.

validate(options: {
  rules: Record<string, {
    required?: boolean,
    minlength?: number,
    email?: boolean
  }>,
  messages?: Record<string, {
    required?: string,
    minlength?: string,
    email?: string
  }>,
  errorClass?: string,
  submitHandler?: (form: HTMLFormElement, event?: Event) => void
}): this

Default Settings

  • errorClass ➡ "error"
  • submitHandler ➡ form.submit()

Behavior

  1. On submit, iterates fields in rules.
  2. Checks:
    • required: non‐empty
    • minlength: length ≥ specified
    • email: pattern /\S+@\S+\.\S+/
  3. Inserts/updates a <span class="error"> after each field.
  4. Prevents submit if any rule fails; otherwise calls submitHandler.

Example

$("#signupForm").validate({
  rules: {
    username: { required: true, minlength: 3 },
    email:    { required: true, email: true }
  },
  messages: {
    username: {
      required:  "Please enter a username.",
      minlength: "Username must be at least 3 characters."
    },
    email: {
      email: "Enter a valid email address."
    }
  },
  errorClass: "form-error",
  submitHandler(form) {
    // Custom AJAX submission
    fetch("/api/signup", {
      method: "POST",
      body: new FormData(form)
    }).then(() => alert("Signed up!"));
  }
});

Usage Summary

// 1. DOM Ready
$(document).ready(() => {
  // 2. Event binding
  $(".todo-list")
    .on("click", ".delete", e => e.target.closest("li").remove())
    // 3. Fade effects with delay
    .fadeOut(300)
    .delay(200)
    .fadeIn(300);
  
  // 4. Form validation
  $("#contactForm").validate({ /* …options… */ });
});

With only ~100 lines of code, this file delivers a concise, chainable, and dependency-free subset of common jQuery features.