Explore snippets
Discover reusable code snippets, examples, fixes, and ideas shared by developers, students, and teams.
FAQ Section Markup
A simple FAQ section using semantic HTML and details/summary elements.
<section class="faq-section" aria-labelledby="faq-title">
<h2 id="faq-title">Frequently asked questions</h2>
<details>
<summary>Can I use CodShot for free?</summary>
<p>Yes. The free plan is a good way to try the platform.</p>
</details>
Cross-Tab State Sync with BroadcastChannel
Synchronize lightweight UI state between tabs from the same origin.
const channel = new BroadcastChannel('app-preferences');
const preferences = {
theme: 'dark',
compactMode: true,
};
channel.addEventListener('message', (event) => {
if (event.data?.type !== 'preferences-updated') {
return;
}
Web Worker for CPU-Heavy Calculations
Move expensive calculations off the main thread and return the result with postMessage.
// statistics.worker.js
self.addEventListener('message', (event) => {
const numbers = event.data;
const total = numbers.reduce(
(sum, value) => sum + value,
0,
);
self.postMessage({
total,
average: numbers.length
Infinite Scroll with IntersectionObserver
Load the next page when a sentinel approaches the viewport and prevent duplicate requests.
const sentinel = document.querySelector('[data-load-more]');
let page = 1;
let isLoading = false;
let hasMore = true;
const observer = new IntersectionObserver(
async (entries) => {
const entry = entries[0];
TypeScript Discriminated Union Reducer
Model reducer actions safely with exhaustive TypeScript checking.
type State = {
count: number;
label: string;
};
type Action =
| {
type: 'increment';
amount: number;
}
| {
type: 'rename';
label: string;
}
| {
type: 'reset';
};
export function reducer(
state: State,
Typed JSON Fetch Helper
Wrap fetch with JSON parsing, typed responses, and useful HTTP error messages.
type ApiErrorBody = {
message?: string;
};
export async function fetchJson<T>(
input: RequestInfo | URL,
init?: RequestInit,
): Promise<T> {
const response = await fetch(input, {
...init,
headers: {
Accept: 'application/json',
Async Generator for Paginated API Data
Iterate through paginated API responses without loading every page into memory.
type Page<T> = {
items: T[];
nextCursor: string | null;
};
export async function* paginate<T>(
buildUrl: (cursor: string | null) => string,
): AsyncGenerator<T, void, void> {
let cursor: string | null = null;
do {
Process Mixed Results with Promise.allSettled
Run independent asynchronous tasks and keep both successful and failed outcomes.
async function loadDashboardResources() {
const requests = [
fetch('/api/profile').then((response) => response.json()),
fetch('/api/projects').then((response) => response.json()),
fetch('/api/notifications').then((response) => response.json()),
URLSearchParams Filter State
Read, update, and remove page filters without manually concatenating query strings.
function updateFilters(changes) {
const url = new URL(window.location.href);
Object.entries(changes).forEach(([key, value]) => {
const normalizedValue = String(value ?? '').trim();
if (normalizedValue === '') {
url.searchParams.delete(key);
Abortable Fetch with Timeout
Cancel a slow fetch request with AbortController while preserving the caller signal.
type FetchWithTimeoutOptions = RequestInit & {
timeoutMs?: number;
};
export async function fetchWithTimeout(
input: RequestInfo | URL,
options: FetchWithTimeoutOptions = {},
): Promise<Response> {
const {
timeoutMs = 8000,
Fetch POST JSON Request
Send JSON data to a backend endpoint with fetch.
async function createNote(note) {
const response = await fetch('/api/notes', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(note)
});
if (!response.ok) {
Fetch GET Request
Load JSON from an API endpoint with async and await.
async function searchSnippets(query) {
const url = `/api/snippets?search=${encodeURIComponent(query)}`;
const response = await fetch(url);
if (!response.ok) {
throw new Error('Search request failed.');
}
Bootstrap Toast Notification
Show a Bootstrap 5 toast message from JavaScript.
<button class="btn btn-primary" id="showToastBtn">Show toast</button>
<div class="toast-container position-fixed bottom-0 end-0 p-3">
<div id="demoToast" class="toast" role="status" aria-live="polite" aria-atomic="true">
<div class="toast-header">
Save UI State to localStorage
Remember a simple UI preference in localStorage.
const checkbox = document.querySelector('#compactMode');
const savedValue = localStorage.getItem('compactMode');
checkbox.checked = savedValue === '1';
document.body.classList.toggle('compact', checkbox.checked);
checkbox.addEventListener('change', () => {
Fetch JSON with Error Handling
Fetch JSON data and handle HTTP errors cleanly.
async function loadProfile() {
const response = await fetch('/api/profile');
if (!response.ok) {
throw new Error(`Request failed: ${response.status}`);
}
return await response.json();
}
loadProfile()
Simple Form Validation
Validate a small form before submitting it.
const form = document.querySelector('#contactForm');
const emailInput = document.querySelector('#email');
const messageBox = document.querySelector('#formMessage');
form.addEventListener('submit', (event) => {
messageBox.textContent = '';
Event Delegation for Buttons
Handle clicks for many dynamic buttons with one event listener.
const list = document.querySelector('#todoList');
list.addEventListener('click', (event) => {
const button = event.target.closest('[data-action]');
if (!button) return;
const item = button.closest('.todo-item');
Toggle Class on Click
Toggle a CSS class on an element when a button is clicked.
const button = document.querySelector('#menuButton');
const menu = document.querySelector('#menu');
button.addEventListener('click', () => {
menu.classList.toggle('is-open');
});
Filter an Array of Objects
A beginner-friendly JavaScript example for filtering objects by search text.
const snippets = [
{ title: 'PHP Slug Generator', language: 'php' },
{ title: 'CSS Loading Spinner', language: 'css' },
{ title: 'JavaScript Debounce', language: 'javascript' }
];
function searchSnippets(items, query) {
Toggle Dark Mode Class
A tiny dark mode toggle that stores the selected mode in localStorage.
const toggleButton = document.querySelector('[data-theme-toggle]');
const savedTheme = localStorage.getItem('theme');
if (savedTheme === 'dark') {
document.documentElement.classList.add('dark');
}
toggleButton?.addEventListener('click', () => {
Save and Load JSON from localStorage
A safe small helper for storing JSON data in localStorage.
function saveJson(key, value) {
localStorage.setItem(key, JSON.stringify(value));
}
function loadJson(key, fallback = null) {
try {
const raw = localStorage.getItem(key);
return raw ? JSON.parse(raw) : fallback;
} catch (error) {
Debounce Function
A reusable debounce helper for search inputs and resize handlers.
function debounce(callback, delay = 300) {
let timerId;
return function (...args) {
clearTimeout(timerId);
timerId = setTimeout(() => {
callback.apply(this, args);
}, delay);
};
}
const handleSearch = debounce((event) => {
Copy Text to Clipboard
A vanilla JavaScript helper to copy text to the clipboard with a fallback message.
async function copyText(text) {
try {
await navigator.clipboard.writeText(text);
console.log('Copied to clipboard');
return true;
} catch (error) {
console.error('Clipboard copy failed:', error);
return false;
}
}