Code library

Free snippets & functions

Copy, adapt and use them in your own projects.

Intermediate 262 snippets

Bootstrap · Footer with columnsIntermediate
<footer class="container py-5 border-top">
  <div class="row">
    <div class="col-12 col-md">
      <strong>Brand</strong>
      <small class="d-block text-body-secondary">&copy; 2026</small>
    </div>
    <div class="col-6 col-md">
      <h5>Product</h5>
      <ul class="list-unstyled small">
        <li><a class="link-secondary text-decoration-none" href="#">Features</a></li>
        <li><a class="link-secondary text-decoration-none" href="#">Pricing</a></li>
      </ul>
    </div>
    <div class="col-6 col-md">
      <h5>Company</h5>
      <ul class="list-unstyled small">
        <li><a class="link-secondary text-decoration-none" href="#">About</a></li>
        <li><a class="link-secondary text-decoration-none" href="#">Blog</a></li>
      </ul>
    </div>
  </div>
</footer>

Links grouped into columns.

Bootstrap · Split hero with imageIntermediate
<section class="container py-5">
  <div class="row align-items-center g-5">
    <div class="col-lg-6 order-2 order-lg-1">
      <h1 class="display-5 fw-bold lh-1 mb-3">Build faster with less code</h1>
      <p class="lead">Short paragraph explaining the value of your product.</p>
      <div class="d-grid gap-2 d-sm-flex">
        <a href="#" class="btn btn-primary btn-lg px-4">Get started</a>
        <a href="#" class="btn btn-outline-secondary btn-lg px-4">Learn more</a>
      </div>
    </div>
    <div class="col-lg-6 order-1 order-lg-2">
      <img src="hero.jpg" class="img-fluid rounded-3 shadow" alt="Product screenshot" width="700" height="500">
    </div>
  </div>
</section>

Text on one side, picture on the other.

Bootstrap · Pricing sectionIntermediate
<div class="row row-cols-1 row-cols-md-3 g-4 text-center">
  <div class="col"><div class="card h-100"><div class="card-header"><h4 class="my-0">Free</h4></div><div class="card-body"><h1 class="card-title">$0</h1><ul class="list-unstyled mt-3 mb-4"><li>1 project</li><li>Email support</li></ul><button type="button" class="btn btn-outline-primary w-100">Sign up</button></div></div></div>
  <div class="col"><div class="card h-100 border-primary shadow"><div class="card-header text-bg-primary"><h4 class="my-0">Pro</h4></div><div class="card-body"><h1 class="card-title">$12<small class="text-body-secondary fw-light">/mo</small></h1><ul class="list-unstyled mt-3 mb-4"><li>Unlimited projects</li><li>Priority support</li></ul><button type="button" class="btn btn-primary w-100">Get started</button></div></div></div>
  <div class="col"><div class="card h-100"><div class="card-header"><h4 class="my-0">Team</h4></div><div class="card-body"><h1 class="card-title">$29</h1><ul class="list-unstyled mt-3 mb-4"><li>10 users</li><li>Phone support</li></ul><button type="button" class="btn btn-outline-primary w-100">Contact</button></div></div></div>
</div>

Three plans with the middle one highlighted.

Bootstrap · Live table filterIntermediate
<input type="search" id="filter" class="form-control mb-3" placeholder="Filter..." aria-label="Filter table">
<table class="table" id="people">
  <tbody>
    <tr><td>Ali</td><td>Lahore</td></tr>
    <tr><td>Sara</td><td>Karachi</td></tr>
    <tr><td>Omar</td><td>Islamabad</td></tr>
  </tbody>
</table>

<script>
  document.getElementById('filter').addEventListener('input', function () {
    var q = this.value.toLowerCase();
    document.querySelectorAll('#people tbody tr').forEach(function (tr) {
      tr.classList.toggle('d-none', tr.textContent.toLowerCase().indexOf(q) === -1);
    });
  });
</script>

Type to filter rows.

Bootstrap · Data table with actionsIntermediate
<div class="table-responsive">
  <table class="table align-middle table-hover">
    <thead><tr><th scope="col">Name</th><th scope="col">Status</th><th scope="col" class="text-end">Actions</th></tr></thead>
    <tbody>
      <tr>
        <td>Ali Khan</td>
        <td><span class="badge text-bg-success">Active</span></td>
        <td class="text-end">
          <div class="dropdown">
            <button class="btn btn-sm btn-light" type="button" data-bs-toggle="dropdown" aria-expanded="false" aria-label="Row actions">&#8942;</button>
            <ul class="dropdown-menu dropdown-menu-end">
              <li><a class="dropdown-item" href="#">Edit</a></li>
              <li><a class="dropdown-item text-danger" href="#">Delete</a></li>
            </ul>
          </div>
        </td>
      </tr>
    </tbody>
  </table>
</div>

Status badges and a row menu.

Bootstrap · Dashboard stat cardsIntermediate
<div class="row row-cols-2 row-cols-lg-4 g-3">
  <div class="col"><div class="card text-bg-primary"><div class="card-body"><div class="small">Users</div><div class="fs-3 fw-bold">1,284</div></div></div></div>
  <div class="col"><div class="card text-bg-success"><div class="card-body"><div class="small">Sales</div><div class="fs-3 fw-bold">$9,420</div></div></div></div>
  <div class="col"><div class="card text-bg-warning"><div class="card-body"><div class="small">Pending</div><div class="fs-3 fw-bold">17</div></div></div></div>
  <div class="col"><div class="card text-bg-danger"><div class="card-body"><div class="small">Errors</div><div class="fs-3 fw-bold">3</div></div></div></div>
</div>

Four numbers at the top of a dashboard.

Bootstrap · Admin layout with sidebarIntermediate
<div class="d-flex vh-100">
  <aside class="d-none d-md-flex flex-column flex-shrink-0 p-3 text-bg-dark" style="width: 240px">
    <a href="#" class="fs-4 text-white text-decoration-none mb-3">Admin</a>
    <ul class="nav nav-pills flex-column mb-auto">
      <li class="nav-item"><a href="#" class="nav-link active">Dashboard</a></li>
      <li><a href="#" class="nav-link text-white">Orders</a></li>
      <li><a href="#" class="nav-link text-white">Customers</a></li>
    </ul>
  </aside>
  <main class="flex-grow-1 overflow-auto p-4">
    <h1 class="h3">Dashboard</h1>
  </main>
</div>

A common dashboard skeleton.

Bootstrap · Navbar with dropdown and searchIntermediate
<nav class="navbar navbar-expand-lg bg-body-tertiary">
  <div class="container-fluid">
    <a class="navbar-brand" href="#">App</a>
    <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#nv" aria-controls="nv" aria-expanded="false" aria-label="Toggle navigation"><span class="navbar-toggler-icon"></span></button>
    <div class="collapse navbar-collapse" id="nv">
      <ul class="navbar-nav me-auto mb-2 mb-lg-0">
        <li class="nav-item"><a class="nav-link active" href="#">Home</a></li>
        <li class="nav-item dropdown">
          <a class="nav-link dropdown-toggle" href="#" role="button" data-bs-toggle="dropdown" aria-expanded="false">Products</a>
          <ul class="dropdown-menu">
            <li><a class="dropdown-item" href="#">Software</a></li>
            <li><a class="dropdown-item" href="#">Hardware</a></li>
          </ul>
        </li>
      </ul>
      <form class="d-flex" role="search">
        <input class="form-control me-2" type="search" placeholder="Search" aria-label="Search">
        <button class="btn btn-outline-success" type="submit">Search</button>
      </form>
    </div>
  </div>
</nav>

A realistic main menu.

Bootstrap · Navbar that becomes an offcanvasIntermediate
<nav class="navbar navbar-expand-lg bg-body-tertiary">
  <div class="container">
    <a class="navbar-brand" href="#">Site</a>
    <button class="navbar-toggler" type="button" data-bs-toggle="offcanvas" data-bs-target="#navMenu" aria-controls="navMenu" aria-label="Toggle navigation">
      <span class="navbar-toggler-icon"></span>
    </button>
    <div class="offcanvas-lg offcanvas-end" tabindex="-1" id="navMenu" aria-labelledby="navMenuLabel">
      <div class="offcanvas-header">
        <h5 class="offcanvas-title" id="navMenuLabel">Menu</h5>
        <button type="button" class="btn-close" data-bs-dismiss="offcanvas" data-bs-target="#navMenu" aria-label="Close"></button>
      </div>
      <div class="offcanvas-body">
        <ul class="navbar-nav ms-auto">
          <li class="nav-item"><a class="nav-link" href="#">Home</a></li>
          <li class="nav-item"><a class="nav-link" href="#">Blog</a></li>
        </ul>
      </div>
    </div>
  </div>
</nav>

Desktop bar, mobile slide-in.

Bootstrap · Offcanvas side menuIntermediate
<button class="btn btn-primary" type="button" data-bs-toggle="offcanvas" data-bs-target="#side" aria-controls="side">Menu</button>

<div class="offcanvas offcanvas-start" tabindex="-1" id="side" aria-labelledby="sideLabel">
  <div class="offcanvas-header">
    <h5 class="offcanvas-title" id="sideLabel">Navigation</h5>
    <button type="button" class="btn-close" data-bs-dismiss="offcanvas" aria-label="Close"></button>
  </div>
  <div class="offcanvas-body">
    <div class="list-group list-group-flush">
      <a href="#" class="list-group-item list-group-item-action">Dashboard</a>
      <a href="#" class="list-group-item list-group-item-action">Reports</a>
    </div>
  </div>
</div>

A slide-in panel for mobile menus.

Bootstrap · Toast notificationsIntermediate
<div class="toast-container position-fixed bottom-0 end-0 p-3" id="toasts"></div>

<script>
  function showToast(message, type) {
    var el = document.createElement('div');
    el.className = 'toast align-items-center text-bg-' + (type || 'primary') + ' border-0';
    el.setAttribute('role', 'alert');
    el.setAttribute('aria-live', 'assertive');
    el.setAttribute('aria-atomic', 'true');
    el.innerHTML = '<div class="d-flex"><div class="toast-body"></div>' +
      '<button type="button" class="btn-close btn-close-white me-2 m-auto" data-bs-dismiss="toast" aria-label="Close"></button></div>';
    el.querySelector('.toast-body').textContent = message;      // textContent: safe
    document.getElementById('toasts').appendChild(el);
    el.addEventListener('hidden.bs.toast', function () { el.remove(); });
    new bootstrap.Toast(el, { delay: 4000 }).show();
  }
  showToast('Saved successfully', 'success');
</script>

Small messages that disappear.

Bootstrap · Modal eventsIntermediate
<button type="button" class="btn btn-sm btn-primary" data-bs-toggle="modal" data-bs-target="#view" data-name="Ali">View Ali</button>

<div class="modal fade" id="view" tabindex="-1" aria-hidden="true">
  <div class="modal-dialog"><div class="modal-content"><div class="modal-body">
    <p>User: <strong id="who"></strong></p>
    <input type="text" class="form-control" id="focusMe" aria-label="Note">
  </div></div></div>
</div>

<script>
  var viewModal = document.getElementById('view');
  viewModal.addEventListener('show.bs.modal', function (e) {
    document.getElementById('who').textContent = e.relatedTarget.getAttribute('data-name');
  });
  viewModal.addEventListener('shown.bs.modal', function () { document.getElementById('focusMe').focus(); });
</script>

Pass data from the button to the modal.

Bootstrap · Modal form with AJAX saveIntermediate
<div class="modal fade" id="addModal" tabindex="-1" aria-labelledby="addTitle" aria-hidden="true">
  <div class="modal-dialog">
    <form class="modal-content" id="addForm">
      <div class="modal-header">
        <h5 class="modal-title" id="addTitle">Add item</h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
      </div>
      <div class="modal-body">
        <label for="itemName" class="form-label">Name</label>
        <input type="text" class="form-control" id="itemName" name="name" required>
        <div class="text-danger small mt-2" id="addError"></div>
      </div>
      <div class="modal-footer">
        <button type="submit" class="btn btn-primary" id="addBtn">Save</button>
      </div>
    </form>
  </div>
</div>

<script>
  document.getElementById('addForm').addEventListener('submit', async function (e) {
    e.preventDefault();
    var btn = document.getElementById('addBtn');
    btn.disabled = true;
    try {
      var res = await fetch('/api/items', { method: 'POST', body: new FormData(this) });
      if (!res.ok) throw new Error();
      bootstrap.Modal.getOrCreateInstance(document.getElementById('addModal')).hide();
      this.reset();
    } catch (err) {
      document.getElementById('addError').textContent = 'Could not save. Try again.';
    } finally { btn.disabled = false; }
  });
</script>

Submit without leaving the page, then close the modal.

Bootstrap · Show server-side errorsIntermediate
<form method="post" novalidate>
  <div class="mb-3">
    <label for="mail" class="form-label">Email</label>
    <input type="email" name="email" id="mail" class="form-control is-invalid" value="not-an-email" aria-describedby="mail-err">
    <div id="mail-err" class="invalid-feedback">Enter a valid email address.</div>
  </div>
  <div class="mb-3">
    <label for="pw2" class="form-label">Password</label>
    <input type="password" name="password" id="pw2" class="form-control is-valid">
  </div>
  <button type="submit" class="btn btn-primary">Save</button>
</form>
<!-- PHP: add " is-invalid" to the class when $errors has an entry for the field -->

Mark fields invalid from the server response.

Bootstrap · Client-side form validationIntermediate
<form class="needs-validation" novalidate>
  <div class="mb-3">
    <label for="n" class="form-label">Name</label>
    <input type="text" class="form-control" id="n" required>
    <div class="invalid-feedback">Please enter your name.</div>
    <div class="valid-feedback">Looks good!</div>
  </div>
  <button class="btn btn-primary" type="submit">Submit</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>

Show Bootstrap feedback using the browser's validation.

Bootstrap · Customize with CSS variablesIntermediate
<style>
  :root {
    --bs-primary: #7c3aed;
    --bs-primary-rgb: 124, 58, 237;
    --bs-link-color-rgb: 124, 58, 237;
    --bs-border-radius: 0.75rem;
  }
  .btn-primary {
    --bs-btn-bg: #7c3aed;
    --bs-btn-border-color: #7c3aed;
    --bs-btn-hover-bg: #6d28d9;
    --bs-btn-hover-border-color: #6d28d9;
    --bs-btn-active-bg: #5b21b6;
  }
</style>
<button type="button" class="btn btn-primary">Purple button</button>

Change colors without Sass.

Bootstrap · Dark mode toggleIntermediate
<button type="button" class="btn btn-outline-secondary" id="themeBtn">Toggle theme</button>

<script>
  (function () {
    var root = document.documentElement;
    var saved = null;
    try { saved = localStorage.getItem('theme'); } catch (e) {}
    var prefersDark = window.matchMedia && matchMedia('(prefers-color-scheme: dark)').matches;
    root.setAttribute('data-bs-theme', saved || (prefersDark ? 'dark' : 'light'));

    document.getElementById('themeBtn').addEventListener('click', function () {
      var next = root.getAttribute('data-bs-theme') === 'dark' ? 'light' : 'dark';
      root.setAttribute('data-bs-theme', next);
      try { localStorage.setItem('theme', next); } catch (e) {}
    });
  })();
</script>

Bootstrap 5.3 themes switch with one attribute on the html element.

HTML · A form with live outputIntermediate
<form oninput="total.value = Number(qty.value) * 20">
  <label for="qty">Quantity</label>
  <input id="qty" name="qty" type="number" value="1" min="1">
  <p>Total: <output name="total" for="qty">20</output> USD</p>
</form>

The output element shows a calculated value.

HTML · International text: ruby and bdiIntermediate
<p><ruby>漢<rp>(</rp><rt>kan</rt><rp>)</rp></ruby> is a Chinese character.</p>
<p>User <bdi>إيان</bdi> scored 90 points.</p>
<p><bdo dir="rtl">This text is reversed.</bdo></p>

Small helpers for other languages.

HTML · Image mapsIntermediate
<img src="floor.png" alt="Office floor plan" usemap="#plan" width="600" height="400">
<map name="plan">
  <area shape="rect" coords="0,0,300,200" href="/room-a" alt="Room A">
  <area shape="circle" coords="450,100,50" href="/lobby" alt="Lobby">
</map>

Clickable regions on one image.

HTML · The base tagIntermediate
<!DOCTYPE html>
<html lang="en">
<head>
  <base href="https://example.com/docs/" target="_self">
  <title>Docs</title>
</head>
<body>
  <a href="intro.html">Relative to the base</a>
</body>
</html>

Sets a starting address for all relative links.

HTML · data attributesIntermediate
<button type="button" class="buy" data-product-id="42" data-price="19.99" data-name="Notebook">Buy</button>

<script>
  document.querySelector('.buy').addEventListener('click', function () {
    const d = this.dataset;                       // d.productId, d.price, d.name
    console.log(d.productId, Number(d.price), d.name);
  });
</script>

Pass small values from HTML to JavaScript.

HTML · template and slotIntermediate
<template id="card-tpl">
  <style>.card { border: 1px solid #ddd; padding: 1rem; border-radius: 8px; }</style>
  <div class="card">
    <slot name="title">Default title</slot>
    <slot></slot>
  </div>
</template>

<my-card>
  <h3 slot="title">Hello</h3>
  <p>Content goes into the default slot.</p>
</my-card>

Reusable markup that does nothing until you use it.

HTML · Print button and print linkIntermediate
<button type="button" onclick="window.print()">Print this page</button>
<link rel="stylesheet" href="print.css" media="print">

A print stylesheet is loaded only when printing.

HTML · Responsive video embedIntermediate
<div style="aspect-ratio:16/9;max-width:720px">
  <iframe src="https://www.youtube-nocookie.com/embed/VIDEO_ID" title="Video title" style="width:100%;height:100%;border:0" loading="lazy" allowfullscreen></iframe>
</div>

Keep the 16:9 shape at any width.

HTML · A basic HTML emailIntermediate
<table role="presentation" width="100%" cellpadding="0" cellspacing="0" style="background:#f3f4f6;padding:24px 0">
  <tr>
    <td align="center">
      <table role="presentation" width="600" cellpadding="0" cellspacing="0" style="background:#ffffff;border-radius:8px">
        <tr><td style="padding:24px;font-family:Arial,sans-serif;font-size:16px;color:#111827">
          <h1 style="margin:0 0 12px;font-size:22px">Welcome!</h1>
          <p style="margin:0 0 16px">Thanks for joining us.</p>
          <a href="https://example.com/start" style="display:inline-block;padding:12px 20px;background:#2563eb;color:#ffffff;text-decoration:none;border-radius:6px">Get started</a>
        </td></tr>
      </table>
    </td>
  </tr>
</table>

Emails still use tables and inline styles.

<meta http-equiv="Content-Security-Policy" content="default-src 'self'; img-src 'self' data: https:; script-src 'self'; style-src 'self' 'unsafe-inline'; object-src 'none'; base-uri 'self'">

Better as an HTTP header, but a meta tag works for static pages.

HTML · Safer external links and framesIntermediate
<a href="https://other.example/" target="_blank" rel="noopener noreferrer nofollow">External</a>
<iframe src="https://widget.example/" title="Widget" sandbox="allow-scripts allow-same-origin" referrerpolicy="no-referrer" loading="lazy"></iframe>
<img src="https://cdn.example/logo.png" alt="Logo" referrerpolicy="no-referrer" width="100" height="40">

Small attributes that reduce risk.

HTML · Canonical and robots tagsIntermediate
<link rel="canonical" href="https://example.com/page">
<meta name="robots" content="index, follow, max-image-preview:large">
<!-- For a private page: <meta name="robots" content="noindex, nofollow"> -->
<link rel="alternate" hreflang="ur" href="https://example.com/ur/page">
<link rel="alternate" type="application/rss+xml" title="Feed" href="/feed.xml">

Tell search engines which URL is the main one.

HTML · Structured data (JSON-LD)Intermediate
<script type="application/ld+json">
{
  "@context": "https://schema.org",
  "@type": "Article",
  "headline": "How to learn SQL",
  "author": { "@type": "Person", "name": "KB" },
  "datePublished": "2026-11-03",
  "image": "https://example.com/sql.jpg"
}
</script>

Helps search engines understand the page.