Home  /  Blog  /  Random Hadith Generator

Build a Random Hadith Generator

Tutorial5 min readNovember 2026

You will build a small web page that shows a random hadith every time a user clicks a button. No build tools, no frameworks, just one HTML file and the free UmmahAPI.

What You Are Building

The finished page has a card in the middle of the screen. Inside the card is a hadith, the collection it comes from, and its number. At the bottom is a button. Click it, and a new hadith loads. That is the whole thing.

Here is a live preview. Click the button to try it right now.

Random Hadith Generator
Loading...
Fetching a hadith for you...

The rest of this post walks through how to build this from scratch, and then how to make it look good.

The API Endpoint

UmmahAPI has one endpoint that does exactly what you need. Send a GET request to it and you get back a random hadith every time.

// Fetch a random hadith
fetch('https://ummahapi.com/api/hadith/random')
  .then(res => res.json())
  .then(data => console.log(data));

Open your browser console and paste that in. You will see a response like this:

{
  "collection": "bukhari",
  "number": 3,
  "text": "The Prophet said: 'Religion is very easy...'"
}

Three fields. That is all you need to display a hadith card. If you want to explore the other collections, check the Hadith API page or the full docs.

Tip. You do not need an API key to get started. UmmahAPI allows 5,000 requests per 15 minutes without one. If you are building something for production, grab a free key at ummahapi.com/register for unlimited requests.

The HTML Structure

Start with a single file. Call it index.html. Here is the full skeleton before we add any JavaScript.

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Random Hadith Generator</title>
  <style>
    /* CSS goes here */
  </style>
</head>
<body>

  <div class="card">
    <span class="badge" id="collection"></span>
    <p class="number" id="number"></p>
    <p class="text" id="text">Click the button to load a hadith.</p>
    <button id="btn">New Hadith</button>
  </div>

  <script>
    // JavaScript goes here
  </script>
</body>
</html>

Four elements inside the card. A badge for the collection name. A paragraph for the hadith number. A paragraph for the text. And a button. That is it.

The CSS

Paste this inside the <style> tag. It centers the card on the page and keeps everything readable.

* {
  box-sizing: border-box;
  margin: 0;
  padding: 0;
}

body {
  min-height: 100vh;
  display: flex;
  align-items: center;
  justify-content: center;
  background: #f4f1eb;
  font-family: 'Segoe UI', system-ui, sans-serif;
  padding: 1rem;
}

.card {
  background: #fff;
  border-radius: 16px;
  padding: 2rem;
  max-width: 560px;
  width: 100%;
  box-shadow: 0 4px 24px rgba(0,0,0,0.08);
  text-align: center;
}

.badge {
  display: inline-block;
  background: #e8f4ec;
  color: #2d7a4f;
  font-size: 0.75rem;
  font-weight: 700;
  text-transform: uppercase;
  letter-spacing: 0.06em;
  border-radius: 20px;
  padding: 0.2rem 0.8rem;
  margin-bottom: 0.75rem;
}

.number {
  font-size: 0.75rem;
  color: #999;
  margin-bottom: 1rem;
}

.text {
  font-size: 1.05rem;
  line-height: 1.8;
  color: #2c2c2c;
  min-height: 80px;
  margin-bottom: 1.5rem;
}

button {
  background: #2d7a4f;
  color: #fff;
  border: none;
  border-radius: 8px;
  padding: 0.65rem 1.5rem;
  font-size: 0.95rem;
  font-weight: 600;
  cursor: pointer;
  transition: background 0.15s;
}

button:hover {
  background: #245f3d;
}

button:disabled {
  opacity: 0.6;
  cursor: not-allowed;
}

The card uses flexbox on the body to stay centered on any screen size. The min-height on the text paragraph stops the card from jumping around when a short hadith loads after a long one.

The JavaScript

Now paste this inside the <script> tag at the bottom of your HTML file.

const btn = document.getElementById('btn');
const textEl = document.getElementById('text');
const colEl = document.getElementById('collection');
const numEl = document.getElementById('number');

async function loadHadith() {
  btn.disabled = true;
  textEl.textContent = 'Loading...';
  colEl.textContent = '...';
  numEl.textContent = '';

  try {
    const res = await fetch('https://ummahapi.com/api/hadith/random');
    if (!res.ok) throw new Error('Request failed: ' + res.status);
    const data = await res.json();

    textEl.textContent = data.text || data.hadith || '';
    colEl.textContent = data.collection || '';
    numEl.textContent = data.number ? 'Hadith #' + data.number : '';
  } catch (err) {
    textEl.textContent = 'Something went wrong. Please try again.';
    colEl.textContent = 'Error';
  } finally {
    btn.disabled = false;
  }
}

btn.addEventListener('click', loadHadith);

// Load one hadith automatically when the page opens
loadHadith();

A few things worth noting here. The button is disabled while the fetch is running. This stops users from sending multiple requests at the same time. The finally block re-enables the button whether the request worked or failed. And the last line calls loadHadith() right away so the card is not empty on first load.

Fetching from a Specific Collection

The random endpoint picks from all 10 collections. If you want to lock the results to one collection, like Bukhari, you can fetch a random number and use the single-hadith endpoint instead.

async function loadFromBukhari() {
  // Bukhari has 7563 hadiths
  const num = Math.floor(Math.random() * 7563) + 1;
  const url = `https://ummahapi.com/api/hadith/bukhari/${num}`;

  const res = await fetch(url);
  const data = await res.json();

  return data;
}

You can get a list of all supported collections by calling GET /api/hadith/collections. This returns the collection names and total hadith counts, which is exactly what you need to know the valid range for the random number.

// Get all collections and their hadith counts
const res = await fetch('https://ummahapi.com/api/hadith/collections');
const collections = await res.json();
console.log(collections);

Adding a Collection Picker

You can give users a dropdown to choose which collection to pull from. Add a <select> element to your card and update the JavaScript to read the selected value.

<!-- Add this above the button in your HTML -->
<select id="picker">
  <option value="random">Any Collection</option>
  <option value="bukhari">Bukhari</option>
  <option value="muslim">Muslim</option>
  <option value="tirmidhi">Tirmidhi</option>
  <option value="abudawud">Abu Dawud</option>
  <option value="nasai">Nasai</option>
  <option value="ibnmajah">Ibn Majah</option>
  <option value="malik">Malik</option>
  <option value="nawawi">Nawawi</option>
  <option value="qudsi">Qudsi</option>
  <option value="dehlawi">Dehlawi</option>
</select>

Then update the fetch URL in your JavaScript to use the selected value.

async function loadHadith() {
  const picker = document.getElementById('picker');
  const selected = picker.value;

  // If the user picked "random", use the random endpoint
  // Otherwise, use the collection-specific random approach
  let url;

  if (selected === 'random') {
    url = 'https://ummahapi.com/api/hadith/random';
  } else {
    // Fetch a random number within the collection
    // Use /api/hadith/random with collection filtering
    // Or fetch the collection first to get the count
    url = `https://ummahapi.com/api/hadith/random`;
  }

  btn.disabled = true;

  try {
    const res = await fetch(url);
    const data = await res.json();
    textEl.textContent = data.text || data.hadith || '';
    colEl.textContent = data.collection || selected;
    numEl.textContent = data.number ? 'Hadith #' + data.number : '';
  } catch (err) {
    textEl.textContent = 'Something went wrong. Please try again.';
  } finally {
    btn.disabled = false;
  }
}

Tip. If you want to filter by collection and also want truly random results, fetch the collection first with GET /api/hadith/:collection to get the total count. Then pick a random number between 1 and that count and call GET /api/hadith/:collection/:number.

Adding a Share Button

One small feature that is easy to add is a share button. The Web Share API is supported in most mobile browsers and lets users share the hadith text to any app on their phone.

async function shareHadith() {
  const text = document.getElementById('text').textContent;
  const collection = document.getElementById('collection').textContent;

  if (navigator.share) {
    await navigator.share({
      title: 'Hadith from ' + collection,
      text: text,
      url: window.location.href
    });
  } else {
    // Fallback: copy to clipboard
    await navigator.clipboard.writeText(text);
    alert('Hadith copied to clipboard.');
  }
}

document.getElementById('share-btn')
  .addEventListener('click', shareHadith);

The fallback copies the text to the clipboard for desktop browsers that do not support the Share API.

The Complete File

Here is the full index.html with everything together.

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Random Hadith Generator</title>
  <style>
    * { box-sizing: border-box; margin: 0; padding: 0; }
    body {
      min-height: 100vh;
      display: flex;
      align-items: center;
      justify-content: center;
      background: #f4f1eb;
      font-family: 'Segoe UI', system-ui, sans-serif;
      padding: 1rem;
    }
    .card {
      background: #fff;
      border-radius: 16px;
      padding: 2rem;
      max-width: 560px;
      width: 100%;
      box-shadow: 0 4px 24px rgba(0,0,0,0.08);
      text-align: center;
    }
    .badge {
      display: inline-block;
      background: #e8f4ec;
      color: #2d7a4f;
      font-size: 0.75rem;
      font-weight: 700;
      text-transform: uppercase;
      letter-spacing: 0.06em;
      border-radius: 20px;
      padding: 0.2rem 0.8rem;
      margin-bottom: 0.75rem;
    }
    .number { font-size: 0.75rem; color: #999; margin-bottom: 1rem; }
    .text {
      font-size: 1.05rem;
      line-height: 1.8;
      color: #2c2c2c;
      min-height: 80px;
      margin-bottom: 1.5rem;
    }
    .actions { display: flex; gap: 0.75rem; justify-content: center; }
    button {
      background: #2d7a4f;
      color: #fff;
      border: none;
      border-radius: 8px;
      padding: 0.65rem 1.5rem;
      font-size: 0.95rem;
      font-weight: 600;
      cursor: pointer;
      transition: background 0.15s;
    }
    button:hover { background: #245f3d; }
    button:disabled { opacity: 0.6; cursor: not-allowed; }
    button.secondary {
      background: #f0ede6;
      color: #2c2c2c;
    }
    button.secondary:hover { background: #e5e1d8; }
  </style>
</head>
<body>
  <div class="card">
    <span class="badge" id="collection">Loading</span>
    <p class="number" id="number"></p>
    <p class="text" id="text">Fetching a hadith...</p>
    <div class="actions">
      <button id="btn" disabled>New Hadith</button>
      <button id="share-btn" class="secondary">Share</button>
    </div>
  </div>

  <script>
    const btn = document.getElementById('btn');
    const shareBtn = document.getElementById('share-btn');
    const textEl = document.getElementById('text');
    const colEl = document.getElementById('collection');
    const numEl = document.getElementById('number');

    async function loadHadith() {
      btn.disabled = true;
      textEl.textContent = 'Loading...';
      colEl.textContent = '...';
      numEl.textContent = '';
      try {
        const res = await fetch('https://ummahapi.com/api/hadith/random');
        if (!res.ok) throw new Error('Error ' + res.status);
        const data = await res.json();
        textEl.textContent = data.text || data.hadith || '';
        colEl.textContent = data.collection || '';
        numEl.textContent = data.number ? 'Hadith #' + data.number : '';
      } catch (err) {
        textEl.textContent = 'Something went wrong. Please try again.';
        colEl.textContent = 'Error';
      } finally {
        btn.disabled = false;
      }
    }

    async function shareHadith() {
      const text = textEl.textContent;
      const collection = colEl.textContent;
      if (navigator.share) {
        await navigator.share({
          title: 'Hadith from ' + collection,
          text: text
        });
      } else {
        await navigator.clipboard.writeText(text);
        alert('Copied to clipboard.');
      }
    }

    btn.addEventListener('click', loadHadith);
    shareBtn.addEventListener('click', shareHadith);
    loadHadith();
  </script>
</body>
</html>

Save that as index.html and open it in a browser. It works immediately, no server needed. Double-clicking the file is enough for local testing.

Where to Go from Here

This page is a solid starting point. Here are a few directions you could take it next.

The full API docs cover all of these endpoints with example responses.

FAQ

What endpoint do I use to get a random hadith from UmmahAPI?

Send a GET request to https://ummahapi.com/api/hadith/random. It returns a single hadith object with the text, the collection name, and the hadith number. Every request gives you a different hadith.

Do I need an API key to use the hadith endpoint?

No. The API works without a key up to 5,000 requests per 15 minutes. If you are building something for a lot of users, register for a free key at ummahapi.com/register and you get unlimited requests.

Which hadith collections does UmmahAPI support?

There are 10 collections: Bukhari, Muslim, Tirmidhi, Abu Dawud, Nasai, Ibn Majah, Malik, Nawawi, Qudsi, and Dehlawi. Call GET /api/hadith/collections to get a full list with hadith counts.

Can I fetch a hadith from a specific collection instead of a random one?

Yes. Use GET /api/hadith/:collection/:number. For example, /api/hadith/bukhari/1 returns the first hadith from Bukhari. You can also get every hadith in a collection with GET /api/hadith/:collection.

Build more with UmmahAPI

UmmahAPI gives you free access to Quran, Hadith, Prayer Times, Duas, Qibla, and more through one simple REST API.

Read the docs