Explore

Explore snippets

Discover reusable code snippets, examples, fixes, and ideas shared by developers, students, and teams.

Public snippets by CodShot user
Clear
23 public snippets
Open
HTML / Markup
Public

FAQ Section Markup

A simple FAQ section using semantic HTML and details/summary elements.

HTML / Markup Preview
<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>
#html #faq #semantic #beginner
CodShot user
CodShot user
Updated: 2026-09-05 16:52
Public snippets
0 #58
Open
JavaScript
Public

Cross-Tab State Sync with BroadcastChannel

Synchronize lightweight UI state between tabs from the same origin.

JavaScript Preview
const channel = new BroadcastChannel('app-preferences');

const preferences = {
  theme: 'dark',
  compactMode: true,
};

channel.addEventListener('message', (event) => {
  if (event.data?.type !== 'preferences-updated') {
    return;
  }
#javascript #broadcastchannel #browser-api #state
CodShot user
CodShot user
Updated: 2026-08-06 18:36
Public snippets
0 #240
Open
JavaScript
Public

Web Worker for CPU-Heavy Calculations

Move expensive calculations off the main thread and return the result with postMessage.

JavaScript Preview
// 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
#javascript #web-worker #performance #frontend
CodShot user
CodShot user
Updated: 2026-08-06 18:36
Public snippets
0 #238
Open
JavaScript
Public

Infinite Scroll with IntersectionObserver

Load the next page when a sentinel approaches the viewport and prevent duplicate requests.

JavaScript Preview
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];
#javascript #intersection-observer #infinite-scroll #performance
CodShot user
CodShot user
Updated: 2026-08-06 18:36
Public snippets
0 #237
Open
TypeScript
Public

TypeScript Discriminated Union Reducer

Model reducer actions safely with exhaustive TypeScript checking.

TypeScript Preview
type State = {
  count: number;
  label: string;
};

type Action =
  | {
      type: 'increment';
      amount: number;
    }
  | {
      type: 'rename';
      label: string;
    }
  | {
      type: 'reset';
    };

export function reducer(
  state: State,
#typescript #reducer #state #validation
CodShot user
CodShot user
Updated: 2026-08-06 18:36
Public snippets
0 #236
Open
TypeScript
Public

Typed JSON Fetch Helper

Wrap fetch with JSON parsing, typed responses, and useful HTTP error messages.

TypeScript Preview
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',
#typescript #fetch #api #json
CodShot user
CodShot user
Updated: 2026-08-06 18:36
Public snippets
0 #235
Open
TypeScript
Public

Async Generator for Paginated API Data

Iterate through paginated API responses without loading every page into memory.

TypeScript Preview
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 {
#typescript #async #pagination #api
CodShot user
CodShot user
Updated: 2026-08-06 18:36
Public snippets
0 #234
Open
JavaScript
Public

Process Mixed Results with Promise.allSettled

Run independent asynchronous tasks and keep both successful and failed outcomes.

JavaScript Preview
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()),
#javascript #promise #async #error-handling
CodShot user
CodShot user
Updated: 2026-08-06 18:36
Public snippets
0 #233
Open
JavaScript
Public

URLSearchParams Filter State

Read, update, and remove page filters without manually concatenating query strings.

JavaScript Preview
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);
#javascript #urlsearchparams #filter #frontend
CodShot user
CodShot user
Updated: 2026-08-06 18:36
Public snippets
0 #232
Open
TypeScript
Public

Abortable Fetch with Timeout

Cancel a slow fetch request with AbortController while preserving the caller signal.

TypeScript Preview
type FetchWithTimeoutOptions = RequestInit & {
  timeoutMs?: number;
};

export async function fetchWithTimeout(
  input: RequestInfo | URL,
  options: FetchWithTimeoutOptions = {},
): Promise<Response> {
  const {
    timeoutMs = 8000,
#typescript #fetch #abortcontroller #error-handling
CodShot user
CodShot user
Updated: 2026-08-06 18:36
Public snippets
0 #231
Open
JavaScript
Public

Fetch POST JSON Request

Send JSON data to a backend endpoint with fetch.

JavaScript Preview
async function createNote(note) {
    const response = await fetch('/api/notes', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify(note)
    });

    if (!response.ok) {
#api #javascript #post #json
CodShot user
CodShot user
Updated: 2026-06-08 14:33
Public snippets
0 #125
Open
JavaScript
Public

Fetch GET Request

Load JSON from an API endpoint with async and await.

JavaScript Preview
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.');
    }
#api #javascript #fetch #json
CodShot user
CodShot user
Updated: 2026-06-08 14:33
Public snippets
0 #124
Open
HTML / Markup
Public

Bootstrap Toast Notification

Show a Bootstrap 5 toast message from JavaScript.

HTML / Markup Preview
<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">
#bootstrap #toast #ui #javascript
CodShot user
CodShot user
Updated: 2026-06-08 14:33
Public snippets
0 #119
Open
JavaScript
Public

Save UI State to localStorage

Remember a simple UI preference in localStorage.

JavaScript Preview
const checkbox = document.querySelector('#compactMode');
const savedValue = localStorage.getItem('compactMode');

checkbox.checked = savedValue === '1';
document.body.classList.toggle('compact', checkbox.checked);

checkbox.addEventListener('change', () => {
#javascript #localstorage #ui #state
CodShot user
CodShot user
Updated: 2026-06-08 14:33
Public snippets
0 #118
Open
JavaScript
Public

Fetch JSON with Error Handling

Fetch JSON data and handle HTTP errors cleanly.

JavaScript Preview
async function loadProfile() {
    const response = await fetch('/api/profile');

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

    return await response.json();
}

loadProfile()
#javascript #fetch #json #error-handling
CodShot user
CodShot user
Updated: 2026-06-08 14:33
Public snippets
0 #117
Open
JavaScript
Public

Simple Form Validation

Validate a small form before submitting it.

JavaScript Preview
const form = document.querySelector('#contactForm');
const emailInput = document.querySelector('#email');
const messageBox = document.querySelector('#formMessage');

form.addEventListener('submit', (event) => {
    messageBox.textContent = '';
#javascript #form #validation #frontend
CodShot user
CodShot user
Updated: 2026-06-08 14:33
Public snippets
0 #116
Open
JavaScript
Public

Event Delegation for Buttons

Handle clicks for many dynamic buttons with one event listener.

JavaScript Preview
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');
#javascript #dom #events #performance
CodShot user
CodShot user
Updated: 2026-06-08 14:33
Public snippets
0 #115
Open
JavaScript
Public

Toggle Class on Click

Toggle a CSS class on an element when a button is clicked.

JavaScript Preview
const button = document.querySelector('#menuButton');
const menu = document.querySelector('#menu');

button.addEventListener('click', () => {
    menu.classList.toggle('is-open');
});
#javascript #dom #ui #beginner
CodShot user
CodShot user
Updated: 2026-06-08 14:33
Public snippets
0 #114
Open
JavaScript
Public

Filter an Array of Objects

A beginner-friendly JavaScript example for filtering objects by search text.

JavaScript Preview
const snippets = [
  { title: 'PHP Slug Generator', language: 'php' },
  { title: 'CSS Loading Spinner', language: 'css' },
  { title: 'JavaScript Debounce', language: 'javascript' }
];

function searchSnippets(items, query) {
#javascript #array #filter #beginner
CodShot user
CodShot user
Updated: 2026-06-03 14:05
Public snippets
0 #68
Open
JavaScript
Public

Toggle Dark Mode Class

A tiny dark mode toggle that stores the selected mode in localStorage.

JavaScript Preview
const toggleButton = document.querySelector('[data-theme-toggle]');
const savedTheme = localStorage.getItem('theme');

if (savedTheme === 'dark') {
  document.documentElement.classList.add('dark');
}

toggleButton?.addEventListener('click', () => {
#javascript #dark-mode #ui #localstorage
CodShot user
CodShot user
Updated: 2026-06-03 14:05
Public snippets
0 #67
Open
JavaScript
Public

Save and Load JSON from localStorage

A safe small helper for storing JSON data in localStorage.

JavaScript Preview
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) {
#javascript #localstorage #json #utility
CodShot user
CodShot user
Updated: 2026-06-03 14:05
Public snippets
0 #66
Open
JavaScript
Public

Debounce Function

A reusable debounce helper for search inputs and resize handlers.

JavaScript Preview
function debounce(callback, delay = 300) {
  let timerId;

  return function (...args) {
    clearTimeout(timerId);

    timerId = setTimeout(() => {
      callback.apply(this, args);
    }, delay);
  };
}

const handleSearch = debounce((event) => {
#javascript #debounce #search #utility
CodShot user
CodShot user
Updated: 2026-06-03 14:05
Public snippets
0 #65
Open
JavaScript
Public

Copy Text to Clipboard

A vanilla JavaScript helper to copy text to the clipboard with a fallback message.

JavaScript Preview
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;
  }
}
#javascript #clipboard #utility #beginner
CodShot user
CodShot user
Updated: 2026-06-03 14:05
Public snippets
0 #64
CodShot AI Help
Ask about CodShot features, plans, workspace, AI limits, referrals, and public help topics.
Hi! I can help you understand how CodShot works. What would you like to know?
For account-specific or sensitive issues, please open a support ticket. Open support