#utils Clear
Tags #utils #browser #performance #array #async #dom #objects #pattern #events #format #concurrency #http #ui #advanced #fetch #url #string #functional #cache #files #crypto #promise #intl #observer
JavaScript Scroll to Element Smoothly
Scrolls the page to a target element with an optional pixel offset (useful when a fixed header is present). Uses the native scrollIntoView with smooth behaviour when supported, and falls back to a manual scrollTo with a configurable offset. Pass a CSS selector string or an Element reference.
JavaScript Rate Limiter (Token Bucket)
Implements a token-bucket rate limiter that allows a burst of calls up to a maximum capacity, then replenishes tokens at a steady rate. Useful for throttling outbound API requests, user-facing actions, or any operation where you need to allow occasional bursts without exceeding a sustained rate.
JavaScript Deep Equal Comparison
Performs a recursive structural equality check between two values. Handles primitives, arrays, objects, Dates, Maps, Sets, null, and undefined. Faster than JSON.stringify comparison (which ignores undefined and Map/Set), and avoids the false-positive trap of == or Object.is for nested structures.
JavaScript Calculate Reading Time
Estimates the reading time of a block of text based on an average adult reading speed (default 200 words per minute). Strips HTML tags before counting to handle rich-text content. Returns the result in minutes, rounded up, so a short article always shows at least "1 min read".
JavaScript Generate Initials Avatar (Canvas)
Draws a coloured circular avatar with up to two initials on an HTML5 Canvas and returns it as a data URL. Generates a consistent background colour from the name string so the same user always gets the same colour. Useful as a fallback when a user has no profile photo.
JavaScript Simple State Machine
A lightweight finite state machine that defines valid states and allowed transitions between them. Attempting an invalid transition throws an error. Supports entry/exit hooks per state for side effects. Useful for modelling UI flows (idle → loading → success/error), auth states, and multi-step forms.
JavaScript i18n Minimal Translator
A tiny internationalisation helper that loads a locale dictionary and resolves translation strings by dot-notation key. Supports variable interpolation via {{placeholder}} syntax. Falls back to the key itself when a translation is missing, keeping the UI readable during development. Swap the locale at runtime without a page reload.
JavaScript Queue (Async Task Queue)
A serialised async task queue that executes queued async functions one at a time, in order. Useful for sequencing operations that must not run concurrently (file writes, ordered API mutations, step-by-step wizards). add() returns a Promise that resolves/rejects when that specific task completes.
JavaScript Detect Dark Mode Preference
Reads the user's OS-level dark mode preference using the prefers-color-scheme media query and watches for live changes. Useful for initialising theme state before any user interaction and reacting automatically when the user switches their system theme without reloading the page.
JavaScript Detect Mobile / Device Type
Detects whether the user is on a mobile, tablet, or desktop device. The navigator.userAgentData API (Chromium) is preferred for its structured data; falls back to a User-Agent regex for Safari and Firefox. Useful for conditional rendering, touch event handling, and analytics segmentation.
JavaScript Create Element Helper
A concise helper for creating DOM elements with attributes, properties, styles, event listeners, and children in one call — similar to hyperscript or JSX without a build step. Eliminates repetitive createElement / setAttribute / appendChild chains and keeps DOM construction code readable.
JavaScript DOM Ready Helper
Runs a callback when the DOM is fully parsed and ready, without waiting for images or stylesheets. Works whether called before or after DOMContentLoaded has already fired — unlike a bare addEventListener which misses the event if the DOM is already ready when the script runs.
JavaScript Delegate Event Listener
Attaches a single event listener to a parent element and handles events from matching descendant elements via event delegation. More efficient than attaching listeners to many individual elements, and works for elements added dynamically to the DOM after the listener is registered.
JavaScript Serialize Form to Object
Converts all named form fields into a plain JavaScript object using the FormData API. Handles text inputs, selects, textareas, and checkboxes. Multiple values for the same name (e.g. multi-select, checkboxes) are collected into an array. Ready to JSON.stringify and POST to an API.
JavaScript Cookie Helpers (Get / Set / Delete)
Minimal cookie utilities: getCookie retrieves a value by name, setCookie writes a cookie with optional expiry days and path, deleteCookie removes it by setting an expired date. No library needed for simple first-party cookie management. For complex scenarios (SameSite, Secure, partitioned) extend the options object.
JavaScript Validate URL
Validates whether a string is a well-formed URL using the native URL constructor, which matches browser parsing behaviour exactly. Optionally restricts to specific protocols (defaults to http and https). No regex maintenance required — if the browser can parse it as a URL, this returns true.
JavaScript Validate Email Address
Validates an email address using a battle-tested regex that covers the vast majority of real-world addresses without being overly strict. For server-side code, pair this with a confirmation email step — client-side regex alone is not a security measure. Returns a boolean for easy conditional use.
JavaScript Hex ↔ RGB Conversion
Converts between hex colour strings (#rrggbb / #rgb) and RGB component objects. hexToRgb parses both shorthand and full hex formats. rgbToHex converts R, G, B integers (0–255) back to a hex string. Handy for colour manipulation, generating CSS variables, and passing colour data between libraries.