Code library

Free snippets & functions

Copy, adapt and use them in your own projects.

Bootstrap · Bootstrap 5 form validationIntermediate
<form class="needs-validation" novalidate>
  <label class="form-label" for="mail">Email</label>
  <input id="mail" type="email" class="form-control" required>
  <div class="invalid-feedback">Please enter a valid email.</div>
  <button class="btn btn-primary mt-3" type="submit">Send</button>
</form>

<script>
document.querySelectorAll('.needs-validation').forEach(function (form) {
  form.addEventListener('submit', function (e) {
    if (!form.checkValidity()) { e.preventDefault(); e.stopPropagation(); }
    form.classList.add('was-validated');
  });
});
</script>

Add novalidate, then switch on Bootstrap’s validation styles when the user presses submit.

CSS · Fluid text with clamp()Intermediate
h1 { font-size: clamp(1.8rem, 4vw + 1rem, 3.5rem); }
p  { font-size: clamp(1rem, 0.9rem + 0.4vw, 1.2rem); }

.section { padding-block: clamp(2rem, 6vw, 5rem); }

clamp(min, preferred, max) lets a size grow with the screen but never get too small or too large.

HTML · Responsive images that load fastIntermediate
<img
  src="photo-800.jpg"
  srcset="photo-400.jpg 400w, photo-800.jpg 800w, photo-1600.jpg 1600w"
  sizes="(max-width: 700px) 100vw, 800px"
  width="800" height="533"
  loading="lazy" decoding="async"
  alt="Describe what the picture shows">

Offer several sizes and let the browser pick the best one. Width and height stop the page from jumping while loading.

HTML · A good <head> for search enginesIntermediate
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>Page title – Site name</title>
  <meta name="description" content="One or two sentences (about 150 characters) that describe this page.">
  <link rel="canonical" href="https://www.example.com/this-page">

  <meta property="og:type"        content="website">
  <meta property="og:title"       content="Page title">
  <meta property="og:description" content="Same short description.">
  <meta property="og:url"         content="https://www.example.com/this-page">
  <meta property="og:image"       content="https://www.example.com/share.jpg">
  <meta name="twitter:card"       content="summary_large_image">
</head>

The tags every public page should have: title, description, canonical address and social-sharing tags.

jQuery · Load more buttonIntermediate
let page = 1;
$('#more').on('click', function () {
  const $btn = $(this).prop('disabled', true).text('Loading…');
  $.get('/items.php', { page: ++page })
    .done(function (html) {
      if ($.trim(html) === '') { $btn.hide(); return; }     // nothing more
      $('#list').append(html);
      $btn.prop('disabled', false).text('Load more');
    })
    .fail(function () {
      $btn.prop('disabled', false).text('Try again');
    });
});

Append the next page of results into a list without reloading. The server returns ready-made HTML.

AJAX · Send a CSRF token with fetch()Intermediate
// HTML:  <meta name="csrf" content="<?= htmlspecialchars($_SESSION['csrf']) ?>">
const token = document.querySelector('meta[name="csrf"]').content;

async function postJson(url, data) {
  const res = await fetch(url, {
    method: 'POST',
    credentials: 'same-origin',
    headers: { 'Content-Type': 'application/json', 'X-CSRF-Token': token },
    body: JSON.stringify(data)
  });
  if (!res.ok) throw new Error('HTTP ' + res.status);
  return res.json();
}

// PHP side:  hash_equals($_SESSION['csrf'], $_SERVER['HTTP_X_CSRF_TOKEN'] ?? '')

Put the token in a meta tag and send it as a header on every POST. The server must compare it with the one stored in the session.

JavaScript · Reveal elements on scrollIntermediate
// CSS:  .reveal{opacity:0;transform:translateY(20px);transition:.6s}
//       .reveal.in{opacity:1;transform:none}
const io = new IntersectionObserver((entries) => {
  entries.forEach((e) => {
    if (e.isIntersecting) {
      e.target.classList.add('in');
      io.unobserve(e.target);       // animate only once
    }
  });
}, { threshold: 0.15 });

document.querySelectorAll('.reveal').forEach((el) => io.observe(el));

IntersectionObserver tells you when an element enters the screen, with no scroll listeners. Pair it with a CSS class that fades the element in.

JavaScript · Throttle a functionIntermediate
function throttle(fn, wait = 100) {
  let last = 0;
  return function (...args) {
    const now = Date.now();
    if (now - last >= wait) {
      last = now;
      fn.apply(this, args);
    }
  };
}

window.addEventListener('scroll', throttle(() => {
  console.log('scrolled to', window.scrollY);
}, 200), { passive: true });

Run a function at most once every N milliseconds, for example while the user scrolls. (Debounce waits until the user stops; throttle runs regularly.)

JavaScript · fetch() with a timeoutIntermediate
async function fetchJson(url, ms = 8000) {
  const ctrl = new AbortController();
  const timer = setTimeout(() => ctrl.abort(), ms);
  try {
    const res = await fetch(url, { signal: ctrl.signal, headers: { Accept: 'application/json' } });
    if (!res.ok) throw new Error('HTTP ' + res.status);
    return await res.json();
  } finally {
    clearTimeout(timer);
  }
}

fetch() waits forever by default. AbortController lets you give up after a few seconds.

SQL · Insert or update in one queryIntermediate
INSERT INTO settings (k, v)
VALUES ('site_name', 'My site')
ON DUPLICATE KEY UPDATE v = VALUES(v);

-- Counter example
INSERT INTO page_views (page, views) VALUES ('/home', 1)
ON DUPLICATE KEY UPDATE views = views + 1;

If the row already exists (same unique key), update it; otherwise insert it. The table needs a PRIMARY or UNIQUE key on the column.

SQL · Add an index to speed up a queryIntermediate
-- Single column
CREATE INDEX idx_orders_customer ON orders (customer_id);

-- Two columns: useful for  WHERE status = ? ORDER BY created_at
CREATE INDEX idx_orders_status_date ON orders (status, created_at);

-- Check it is used (look at the "key" column)
EXPLAIN SELECT * FROM orders WHERE status = 'paid' ORDER BY created_at DESC LIMIT 20;

An index helps columns used in WHERE, JOIN and ORDER BY. Too many indexes slow down writes, so add them for real queries and check with EXPLAIN.

SQL · GROUP BY with HAVINGIntermediate
-- Customers who spent more than 1000 in 2026
SELECT customer_id, COUNT(*) AS orders, SUM(total) AS spent
FROM orders
WHERE created_at >= '2026-01-01' AND created_at < '2027-01-01'
GROUP BY customer_id
HAVING SUM(total) > 1000
ORDER BY spent DESC;

WHERE filters rows before they are grouped; HAVING filters the groups afterwards.

PHP · Send a plain email with mail()Intermediate
function clean_header(string $v): string
{
    return trim(preg_replace('/[\r\n]+/', ' ', $v));
}

$to      = 'you@example.com';
$subject = clean_header('New message from ' . $_POST['name']);
$body    = "Name: " . $_POST['name'] . "\nEmail: " . $_POST['email'] . "\n\n" . $_POST['message'];
$headers = [
    'From'         => 'website@example.com',                 // your own address, not the visitor's
    'Reply-To'     => clean_header($_POST['email']),
    'Content-Type' => 'text/plain; charset=UTF-8',
];

mail($to, $subject, $body, $headers);   // array headers need PHP 7.2 or newer

Strip line breaks from anything that goes into a header, otherwise attackers can inject extra headers (header injection). On servers like WampServer, mail() us…

PHP · Send basic security headersIntermediate
header('X-Content-Type-Options: nosniff');
header('X-Frame-Options: SAMEORIGIN');
header('Referrer-Policy: strict-origin-when-cross-origin');
header('Permissions-Policy: camera=(), microphone=(), geolocation=()');
header("Content-Security-Policy: default-src 'self'; img-src 'self' data:; frame-ancestors 'self'");

// Only on HTTPS sites. Tells browsers to always use HTTPS for a year.
if (!empty($_SERVER['HTTPS'])) {
    header('Strict-Transport-Security: max-age=31536000; includeSubDomains');
}

A few headers that close common attack routes. Test your Content-Security-Policy before you enforce it, because it blocks inline scripts.

PHP · Call a JSON API with cURLIntermediate
function api_get(string $url): array
{
    $ch = curl_init($url);
    curl_setopt_array($ch, [
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_CONNECTTIMEOUT => 5,
        CURLOPT_TIMEOUT        => 10,
        CURLOPT_FOLLOWLOCATION => false,
        CURLOPT_HTTPHEADER     => ['Accept: application/json'],
    ]);
    $body = curl_exec($ch);
    $code = (int)curl_getinfo($ch, CURLINFO_HTTP_CODE);
    $err  = curl_error($ch);
    curl_close($ch);

    if ($body === false)  throw new RuntimeException('Request failed: ' . $err);
    if ($code !== 200)    throw new RuntimeException('API returned HTTP ' . $code);
    return json_decode($body, true, 512, JSON_THROW_ON_ERROR);
}

A GET request with a timeout and proper error checks. Always set timeouts so a slow API cannot freeze your page.

PHP · Serve a private file safelyIntermediate
$dir  = '/var/private-files';                       // NOT inside the web root
$name = basename((string)($_GET['file'] ?? ''));    // strips any folder part
$path = $dir . '/' . $name;

// ... check here that the logged-in user is allowed to get this file ...

if ($name === '' || !is_file($path)) { http_response_code(404); exit('Not found'); }

header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="' . rawurlencode($name) . '"');
header('Content-Length: ' . filesize($path));
header('X-Content-Type-Options: nosniff');
readfile($path);
exit;

Keep private files outside the web root and send them through PHP after checking who is asking. basename() blocks ../ tricks.

Bootstrap · Helper classesIntermediate
<a href="#content" class="visually-hidden-focusable">Skip to content</a>
<div class="position-relative p-5 border">
  <span class="position-absolute top-50 start-50 translate-middle badge text-bg-dark">Centered</span>
</div>
<div class="clearfix"><img src="a.jpg" class="float-start me-3" width="80" height="80" alt=""><p>Text wraps around the floated image.</p></div>

Small helpers you will use often.

Bootstrap · Focus ring and icon linkIntermediate
<a class="icon-link icon-link-hover" href="#">
  Read more <span aria-hidden="true">&rarr;</span>
</a>
<a href="#" class="d-inline-flex focus-ring py-1 px-2 text-decoration-none border rounded">Custom focus ring</a>
<a href="#" class="link-primary link-offset-2 link-underline-opacity-25 link-underline-opacity-100-hover">Soft underline</a>

New helpers in Bootstrap 5.3.

Bootstrap · Stacked progressIntermediate
<div class="progress-stacked">
  <div class="progress" role="progressbar" aria-label="Segment one" aria-valuenow="15" aria-valuemin="0" aria-valuemax="100" style="width: 15%">
    <div class="progress-bar"></div>
  </div>
  <div class="progress" role="progressbar" aria-label="Segment two" aria-valuenow="30" aria-valuemin="0" aria-valuemax="100" style="width: 30%">
    <div class="progress-bar bg-success"></div>
  </div>
</div>

Several values in one bar.

Bootstrap · Truncate and wrap textIntermediate
<div class="row"><div class="col-6">
  <p class="text-truncate">This very long text is cut with an ellipsis instead of wrapping.</p>
  <p class="text-break">https://example.com/a/really/long/url/that/would/otherwise/overflow/the/column</p>
  <p class="text-nowrap">No wrapping at all</p>
</div></div>

Handle long strings in narrow boxes.

Bootstrap · A fully clickable cardIntermediate
<div class="card" style="width: 18rem">
  <img src="p.jpg" class="card-img-top" alt="">
  <div class="card-body">
    <h5 class="card-title">Article title</h5>
    <p class="card-text">Summary text.</p>
    <a href="/article" class="stretched-link">Read more</a>
  </div>
</div>

The whole card is the link.

Bootstrap · StacksIntermediate
<div class="vstack gap-3">
  <div class="p-2 border">First</div>
  <div class="p-2 border">Second</div>
</div>

<div class="hstack gap-3 mt-3">
  <div class="p-2 border">Left</div>
  <div class="p-2 border ms-auto">Right</div>
  <div class="vr"></div>
  <div class="p-2 border">After divider</div>
</div>

Quick vertical or horizontal layout.

Bootstrap · Reorder columns on mobileIntermediate
<div class="row">
  <div class="col-md-8 order-2 order-md-1">Main content</div>
  <div class="col-md-4 order-1 order-md-2">Sidebar (first on mobile)</div>
</div>

Show the important column first on phones.

Bootstrap · Sticky footerIntermediate
<!DOCTYPE html>
<html lang="en">
<head><meta charset="utf-8"><title>Sticky footer</title></head>
<body class="d-flex flex-column min-vh-100">
  <header class="p-3 border-bottom">Header</header>
  <main class="flex-grow-1 container py-4">Content</main>
  <footer class="mt-auto py-3 bg-body-tertiary text-center">Footer</footer>
</body>
</html>

The footer sits at the bottom of short pages.

Bootstrap · Checklist with list groupIntermediate
<div class="list-group">
  <label class="list-group-item d-flex gap-2">
    <input class="form-check-input flex-shrink-0" type="checkbox" value="" checked>
    <span>Write the code<small class="d-block text-body-secondary">Due today</small></span>
  </label>
  <label class="list-group-item d-flex gap-2">
    <input class="form-check-input flex-shrink-0" type="checkbox" value="">
    <span>Test it<small class="d-block text-body-secondary">Due tomorrow</small></span>
  </label>
</div>

Whole row is clickable.

Bootstrap · Scrollspy navigationIntermediate
<nav id="toc" class="navbar sticky-top bg-body-tertiary">
  <ul class="nav nav-pills">
    <li class="nav-item"><a class="nav-link" href="#s1">One</a></li>
    <li class="nav-item"><a class="nav-link" href="#s2">Two</a></li>
  </ul>
</nav>
<div data-bs-spy="scroll" data-bs-target="#toc" data-bs-offset="80" tabindex="0">
  <section id="s1" style="min-height:80vh"><h2>One</h2></section>
  <section id="s2" style="min-height:80vh"><h2>Two</h2></section>
</div>

The menu highlights the section you are reading.

Bootstrap · Placeholder loading cardsIntermediate
<div class="card" style="width: 18rem" aria-hidden="true">
  <div class="card-body">
    <h5 class="card-title placeholder-glow"><span class="placeholder col-6"></span></h5>
    <p class="card-text placeholder-glow">
      <span class="placeholder col-7"></span>
      <span class="placeholder col-4"></span>
      <span class="placeholder col-8"></span>
    </p>
    <a class="btn btn-primary disabled placeholder col-6" aria-disabled="true"></a>
  </div>
</div>

Skeleton while content loads.

Bootstrap · Responsive video embed with ratioIntermediate
<div class="ratio ratio-16x9">
  <iframe src="https://www.youtube-nocookie.com/embed/VIDEO_ID" title="Video" allowfullscreen loading="lazy"></iframe>
</div>

Keeps 16:9 at any width.

Bootstrap · Gallery with modal previewIntermediate
<div class="row g-2">
  <div class="col-6 col-md-3"><img src="t1.jpg" class="img-fluid rounded my-thumb" data-full="l1.jpg" alt="Photo 1" role="button"></div>
  <div class="col-6 col-md-3"><img src="t2.jpg" class="img-fluid rounded my-thumb" data-full="l2.jpg" alt="Photo 2" role="button"></div>
</div>

<div class="modal fade" id="photoModal" tabindex="-1" aria-label="Photo" aria-hidden="true">
  <div class="modal-dialog modal-lg modal-dialog-centered"><div class="modal-content">
    <img id="photoLarge" src="l1.jpg" class="img-fluid rounded" alt="Large photo">
  </div></div>
</div>

<script>
  document.querySelectorAll('.my-thumb').forEach(function (img) {
    img.addEventListener('click', function () {
      var big = document.getElementById('photoLarge');
      big.src = img.dataset.full; big.alt = img.alt;
      bootstrap.Modal.getOrCreateInstance(document.getElementById('photoModal')).show();
    });
  });
</script>

Click a thumbnail to see it larger.

Bootstrap · A centered login cardIntermediate
<div class="container d-flex align-items-center justify-content-center min-vh-100">
  <div class="card shadow-sm w-100" style="max-width: 400px">
    <div class="card-body p-4">
      <h1 class="h4 mb-4 text-center">Sign in</h1>
      <form>
        <div class="form-floating mb-3"><input type="email" class="form-control" id="le" placeholder="name@example.com"><label for="le">Email</label></div>
        <div class="form-floating mb-3"><input type="password" class="form-control" id="lp" placeholder="Password"><label for="lp">Password</label></div>
        <div class="d-grid"><button class="btn btn-primary" type="submit">Sign in</button></div>
      </form>
    </div>
  </div>
</div>

Vertically centered form.