Back to All Snippets

JavaScript

Vanilla JavaScript utilities and helpers

21 snippets found

Throttle Function

Limits function execution to once per specified time interval

Throttle limits function execution to a regular interval, regardless of how many times the event triggers. Unlike debounce which waits for the end, throttle executes the function immediately then ignores subsequent calls during the interval. Ideal for scroll, resize, or mousemove events.

utilityperformancefunction
function throttle(func, limit) {
  let inThrottle;
  return function(...args) {
    if (!inThrottle) {
      func.apply(this, args);
      inThrottle = true;
      setTimeout(() => inThrottle = false, limit);
    }
  };
}

// Usage
const handleScroll = throttle(() => {
  console.log('Scroll position:', window.scrollY);
}, 100);

window.addEventListener('scroll', handleScroll);

Truncate String

Truncate a string to a specified length with ellipsis

Truncating text while maintaining a precise total length (including ellipsis) is essential for interfaces. This function prevents overflow in cards, lists, or previews. The customizable ending parameter allows using "..." or "…" according to your needs. Indispensable for displaying short descriptions or long titles.

stringutilityformatting
Interactive Playground

Slugify String

Convert a string to a URL-friendly slug

A slug is a URL-friendly version of a title: lowercase, no special characters, spaces replaced with hyphens. This function cleans article titles, product names, or categories to create clean and readable URLs. It removes accents, punctuation, multiple spaces, and leading/trailing hyphens. Essential for SEO and clean URLs.

stringutilityurl
Interactive Playground

Capitalize String

Capitalize first letter or all words in a string

These functions format text for display: capitalize() capitalizes the first letter (for sentences), capitalizeWords() capitalizes each word (for titles). The \b\w regex detects the start of each word. Perfect for formatting usernames, article titles, or normalizing input data.

stringutilityformatting
Interactive Playground

Smooth Scroll to Element

Smoothly scroll to an element on the page

Smooth scroll improves user experience by animating scrolling instead of abrupt jumps. The behavior: "smooth" property of scrollTo() is natively supported. The offset parameter compensates for fixed headers. Perfect for anchor links, tables of contents, or internal navigation. Works well with href="#section" links.

scrollanimationnavigation
function scrollToElement(selector, offset = 0) {
  const element = document.querySelector(selector);
  if (!element) return;

  const elementPosition = element.getBoundingClientRect().top;
  const offsetPosition = elementPosition + window.pageYOffset - offset;

  window.scrollTo({
    top: offsetPosition,
    behavior: 'smooth'
  });
}

// Usage
// Scroll to element with 100px offset from top
scrollToElement('#section-2', 100);

// Set up navigation links
document.querySelectorAll('a[href^="#"]').forEach(anchor => {
  anchor.addEventListener('click', (e) => {
    e.preventDefault();
    scrollToElement(anchor.getAttribute('href'));
  });
});

Random Number in Range

Generate a random number between min and max (inclusive)

Math.random() alone generates numbers between 0 and 1, these functions extend this capability for custom ranges. randomInt() for integers (dice, indices), randomFloat() for decimals (prices, coordinates). The +1 in randomInt ensures max is included. Practical for games, animations, or test data generation.

numberutilityrandom
Interactive Playground

Query Selector Helpers

Shorthand functions for DOM selection

These shortcuts simplify DOM element selection by avoiding repetitive document.querySelector/All. The $$ function automatically converts NodeList to Array, allowing use of array methods like forEach, map, filter. Inspired by jQuery but in modern vanilla JS, it's a significant time-saver for DOM manipulation.

domutilityselector
const $ = (selector) => document.querySelector(selector);
const $$ = (selector) => [...document.querySelectorAll(selector)];

// Usage
const header = $('.header');
const buttons = $$('.btn');

buttons.forEach(btn => {
  btn.addEventListener('click', () => {
    console.log('Button clicked');
  });
});

Clamp Number

Restrict a number to be within a specified range

Clamp forces a number to stay within a defined range: if too small, returns min; if too large, returns max; otherwise returns the number itself. The combination Math.max(num, min) then Math.min(result, max) does it elegantly. Useful for sliders, volumes, zoom levels, opacity, or any control with limits.

numberutility
Interactive Playground

Local Storage Helper

Simple wrapper for localStorage with JSON support and error handling

This wrapper simplifies localStorage usage by automatically handling JSON serialization/deserialization and including robust error handling. It allows storing complex objects without manual conversion, and prevents crashes if storage is full or unavailable (private mode). Perfect for persisting user preferences or session data.

utilitystoragebrowser
const storage = {
  set(key, value) {
    try {
      localStorage.setItem(key, JSON.stringify(value));
      return true;
    } catch (e) {
      console.error('Storage error:', e);
      return false;
    }
  },

  get(key, defaultValue = null) {
    try {
      const item = localStorage.getItem(key);
      return item ? JSON.parse(item) : defaultValue;
    } catch (e) {
      console.error('Storage error:', e);
      return defaultValue;
    }
  },

  remove(key) {
    localStorage.removeItem(key);
  },

  clear() {
    localStorage.clear();
  }
};

// Usage
storage.set('user', { name: 'John', age: 30 });
const user = storage.get('user');

Lazy Load Images

Load images only when they enter the viewport using Intersection Observer

Lazy loading drastically improves performance by loading images only when they become visible. IntersectionObserver is the modern API for detecting when an element enters the viewport, replacing old scroll calculations. Store the URL in data-src instead of src. Reduces initial load time and bandwidth, essential for mobile.

imagesperformancelazy-loading
function lazyLoadImages(selector = 'img[data-src]') {
  const images = document.querySelectorAll(selector);

  const imageObserver = new IntersectionObserver((entries, observer) => {
    entries.forEach(entry => {
      if (entry.isIntersecting) {
        const img = entry.target;
        img.src = img.dataset.src;
        img.removeAttribute('data-src');
        observer.unobserve(img);
      }
    });
  });

  images.forEach(img => imageObserver.observe(img));
}

// Usage
// HTML: <img data-src="image.jpg" alt="Description">
lazyLoadImages();

Date Formatting

Format dates in various common formats

This lightweight function formats dates according to your needs without depending on external libraries like moment.js. It supports common formats (YYYY-MM-DD, DD/MM/YYYY, with times) and uses a simple template system. Ideal for displaying dates in your interfaces or preparing data for APIs.

dateutilityformatting
function formatDate(date, format = 'YYYY-MM-DD') {
  const d = new Date(date);
  const map = {
    YYYY: d.getFullYear(),
    MM: String(d.getMonth() + 1).padStart(2, '0'),
    DD: String(d.getDate()).padStart(2, '0'),
    HH: String(d.getHours()).padStart(2, '0'),
    mm: String(d.getMinutes()).padStart(2, '0'),
    ss: String(d.getSeconds()).padStart(2, '0')
  };

  return format.replace(/YYYY|MM|DD|HH|mm|ss/g, matched => map[matched]);
}

// Usage
formatDate(new Date(), 'YYYY-MM-DD'); // "2024-01-15"
formatDate(new Date(), 'DD/MM/YYYY'); // "15/01/2024"
formatDate(new Date(), 'YYYY-MM-DD HH:mm:ss'); // "2024-01-15 14:30:45"

Form Validation

Simple form validation with common patterns

This collection of validators covers the most common cases: email, phone, URL, min/max lengths, required fields. Each validator returns true/false, making integration into your forms easy. The regex patterns are simple but effective for most cases. URL uses the native URL constructor for robust validation. Reusable and extensible.

validationformregex
const validators = {
  email(value) {
    return /^[^s@]+@[^s@]+.[^s@]+$/.test(value);
  },

  phone(value) {
    return /^+?[ds-()]+$/.test(value);
  },

  url(value) {
    try {
      new URL(value);
      return true;
    } catch {
      return false;
    }
  },

  minLength(value, length) {
    return value.length >= length;
  },

  maxLength(value, length) {
    return value.length <= length;
  },

  required(value) {
    return value !== null && value !== undefined && value.trim() !== '';
  }
};

// Usage
const email = 'user@example.com';
console.log(validators.email(email)); // true
console.log(validators.minLength(email, 5)); // true

Fetch API Wrapper

Enhanced fetch wrapper with error handling and JSON parsing

This wrapper around fetch() simplifies API calls by automatically handling JSON parsing and HTTP errors. Instead of manually handling response.ok and response.json() on every call, this function returns a standardized {data, error} object that makes error handling easier. Ideal for creating a consistent abstraction layer for all your API requests.

apifetchhttp
async function api(url, options = {}) {
  const defaultOptions = {
    headers: {
      'Content-Type': 'application/json',
    },
  };

  try {
    const response = await fetch(url, { ...defaultOptions, ...options });

    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`);
    }

    const data = await response.json();
    return { data, error: null };
  } catch (error) {
    return { data: null, error: error.message };
  }
}

// Usage
const { data, error } = await api('https://api.example.com/users');
if (error) {
  console.error('API Error:', error);
} else {
  console.log('Data:', data);
}

Event Delegation

Efficient event handling using event delegation pattern

Event delegation attaches a single listener to the parent rather than each child, which significantly improves performance with many elements. It even works with elements added dynamically after page load. Instead of 100 listeners on 100 buttons, you have just one on the parent container.

eventsdomperformance
function delegate(parent, selector, event, handler) {
  parent.addEventListener(event, (e) => {
    if (e.target.matches(selector)) {
      handler.call(e.target, e);
    }
  });
}

// Usage
const list = document.querySelector('.item-list');

delegate(list, '.item-button', 'click', function(e) {
  console.log('Button clicked:', this.textContent);
  e.preventDefault();
});

Deep Clone Object

Creates a deep copy of an object or array

This function creates a deep copy of an object, including all nested objects and arrays. Unlike Object.assign() or the spread operator which only make a shallow copy, deepClone recursively copies all levels. Useful for avoiding accidental mutations of shared objects and creating independent copies of complex data structures.

utilityobjectarray
function deepClone(obj) {
  if (obj === null || typeof obj !== 'object') return obj;

  if (obj instanceof Date) return new Date(obj.getTime());
  if (obj instanceof Array) return obj.map(item => deepClone(item));

  if (obj instanceof Object) {
    const copy = {};
    Object.keys(obj).forEach(key => {
      copy[key] = deepClone(obj[key]);
    });
    return copy;
  }
}

// Usage
const original = { name: 'John', details: { age: 30 } };
const cloned = deepClone(original);

Debounce Function

Delays function execution until after a specified wait time has elapsed since the last call

Debounce is essential for optimizing performance during frequent events (search, resize, scroll). It waits until the user has finished interacting before executing the function, avoiding unnecessary calls. Perfect for search fields with autocomplete or form validation.

utilityperformancefunction
function debounce(func, wait) {
  let timeout;
  return function executedFunction(...args) {
    const later = () => {
      clearTimeout(timeout);
      func(...args);
    };
    clearTimeout(timeout);
    timeout = setTimeout(later, wait);
  };
}

// Usage
const handleSearch = debounce((query) => {
  console.log('Searching for:', query);
}, 300);

Copy to Clipboard

Copy text to clipboard with fallback support

This function uses the modern Clipboard API with a fallback for older browsers. navigator.clipboard is asynchronous and more secure, but requires HTTPS. The fallback creates a temporary invisible textarea for the execCommand method. Essential for "Copy code" buttons, link sharing, or token copying. Handles errors gracefully.

clipboardutilitybrowser
async function copyToClipboard(text) {
  // Modern API
  if (navigator.clipboard) {
    try {
      await navigator.clipboard.writeText(text);
      return true;
    } catch (err) {
      console.error('Failed to copy:', err);
    }
  }

  // Fallback for older browsers
  const textarea = document.createElement('textarea');
  textarea.value = text;
  textarea.style.position = 'fixed';
  textarea.style.opacity = '0';
  document.body.appendChild(textarea);
  textarea.select();

  try {
    document.execCommand('copy');
    document.body.removeChild(textarea);
    return true;
  } catch (err) {
    document.body.removeChild(textarea);
    return false;
  }
}

// Usage
const success = await copyToClipboard('Hello, World!');
if (success) {
  console.log('Text copied to clipboard');
}

Cookie Helpers

Simple functions to manage browser cookies

These utilities simplify cookie management by hiding the complex document.cookie syntax. They automatically handle value encoding/decoding, expiration setting, and deletion. Perfect for storing information that must persist between sessions or be sent to the server, like authentication tokens or preferences.

cookiestoragebrowser
const cookies = {
  set(name, value, days = 7) {
    const expires = new Date(Date.now() + days * 864e5).toUTCString();
    document.cookie = `${name}=${encodeURIComponent(value)}; expires=${expires}; path=/`;
  },

  get(name) {
    return document.cookie.split('; ').reduce((r, v) => {
      const parts = v.split('=');
      return parts[0] === name ? decodeURIComponent(parts[1]) : r;
    }, '');
  },

  delete(name) {
    this.set(name, '', -1);
  }
};

// Usage
cookies.set('theme', 'dark', 30);
const theme = cookies.get('theme');
cookies.delete('theme');

Remove Duplicates

Remove duplicate values from an array

Set is the modern and performant solution for removing duplicates from an array. For primitive values (numbers, strings), the Set → Array conversion is sufficient. For objects, uniqueBy() compares a specific property (like an ID) to determine uniqueness. Very useful for cleaning data from APIs or merging lists.

arrayutility
Interactive Playground

Shuffle Array

Randomly shuffle array elements using Fisher-Yates algorithm

The Fisher-Yates algorithm guarantees a truly random and uniform shuffle, unlike naive approaches with sort(). Each permutation has exactly the same probability of occurring. Use it to shuffle cards, randomize quizzes, or create random playlists. The function creates a copy to preserve the original array.

arrayutilityrandom
Interactive Playground

Chunk Array

Split an array into chunks of specified size

This function splits an array into fixed-size sub-arrays, practical for client-side pagination, grid displays, or batch processing. Array.from() with Math.ceil() ensures all elements are included, even if the last chunk is incomplete. Useful for splitting product lists, creating carousels, or processing data in batches.

arrayutility
Interactive Playground