Crafting a Captcha Generator using HTML, CSS and JavaScript

Captcha Generator | Coding Zemigle

A CAPTCHA, short for “Completely Automated Public Turing test to tell Computers and Humans Apart,” is a widely used security mechanism designed to distinguish between human users and automated bots. It serves as a protective barrier on websites to prevent spam, unauthorized access, and malicious activities by ensuring that specific actions can only be performed by real people.

In this tutorial, we will build a simple CAPTCHA generator using only HTML and CSS. CAPTCHAs play a significant role in web security by preventing bots from abusing online services. The traditional form of CAPTCHA involves displaying an image containing distorted text, which users must correctly interpret and enter to proceed.

Advertisement

While modern CAPTCHA solutions, such as Google’s reCAPTCHA, leverage complex backend processing and machine learning to enhance security, our focus will be on creating a basic, front-end-only CAPTCHA. This project is intended for educational purposes and will help demonstrate how simple techniques can be used to add an extra layer of protection to web applications.

Step 1: Setting up the HTML structure of Captcha Generator

First, let’s create the basic structure of our CAPTCHA in HTML. We’ll need an input field for the user to enter the CAPTCHA text, an area to display the CAPTCHA, and a button to submit the form.

✲    index.html
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Captcha Generator | Coding Zemigle</title>
    <link rel="stylesheet" href="style.css" />
    <!-- Fontawesome CDN Link -->
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.2.1/css/all.min.css" />
  </head>
  <body>
    <div class="container">
      <header>Captcha Generator</header>
      <div class="input_field captch_box">
        <input type="text" value="" disabled />
        <button class="refresh_button">
          <i class="fa-solid fa-rotate-right"></i>
        </button>
      </div>
      <div class="input_field captch_input">
        <input type="text" placeholder="Enter captcha" />
      </div>
      <div class="message">Entered captcha is correct</div>
      <div class="input_field button disabled">
        <button>Submit</button>
      </div>
    </div>
    <script src="script.js"></script>
  </body>
</html>

The HTML structure includes a canvas element to draw the CAPTCHA, a button to refresh the CAPTCHA, an input field for the user to enter the CAPTCHA text, and a submit button.

Advertisement

Step 2: Style the Generator with CSS

Next, let’s add some styles to make our CAPTCHA look appealing. Create a style.css file and add the following CSS code:

✲    style.css
* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
  font-family: "Roboto", sans-serif;
}

body {
  height: 100vh;
  display: flex;
  align-items: center;
  justify-content: center;
  background: #D90368;
}

.container {
  position: relative;
  max-width: 320px;
  width: 100%;
  border-radius: 12px;
  padding: 25px;
  background: #fff;
  box-shadow: 0 5px 10px rgba(0, 0, 0, 0.1);
}

header {
  color: #333;
  margin-bottom: 20px;
  font-size: 18px;
  font-weight: 600;
  text-align: center;
}

.input_field {
  position: relative;
  height: 45px;
  margin-top: 25px;
  width: 100%;
}

.refresh_button {
  position: absolute;
  top: 50%;
  right: 10px;
  transform: translateY(-50%);
  background: #D90368;
  height: 30px;
  width: 30px;
  border: none;
  border-radius: 4px;
  color: #fff;
  cursor: pointer;
}

.refresh_button:active {
  transform: translateY(-50%) scale(0.98);
}

.input_field input,
.button button {
  height: 100%;
  width: 100%;
  outline: none;
  border: none;
  border-radius: 8px;
}

.input_field input {
  padding: 0 15px;
  border: 1px solid rgba(0, 0, 0, 0.1);
}

.captch_box input {
  color: #6b6b6b;
  font-size: 22px;
  pointer-events: none;
}

.captch_input input:focus {
  box-shadow: 0 1px 1px rgba(0, 0, 0, 0.08);
}

.message {
  font-size: 14px;
  margin: 14px 0;
  color: #826afb;
  display: none;
}

.message.active {
  display: block;
}

.button button {
  background: #D90368;
  color: #fff;
  cursor: pointer;
  font-weight: 600;
  user-select: none;
}

.button button:active {
  transform: scale(0.99);
}

.button.disabled {
  opacity: 0.6;
  pointer-events: none;
}

The CSS styles ensure that our CAPTCHA form looks clean and user-friendly, with appropriate spacing and styles for the canvas, buttons, and input field.

Advertisement

Step 3: Adding Interactivity with JavaScript

For our CAPTCHA generator to work, we’ll use JavaScript to generate random strings and draw them on the canvas. Create a script.js file and add the following code:

✲    script.js
// Selecting necessary DOM elements
const captchaTextBox = document.querySelector(".captch_box input");
const refreshButton = document.querySelector(".refresh_button");
const captchaInputBox = document.querySelector(".captch_input input");
const message = document.querySelector(".message");
const submitButton = document.querySelector(".button");

// Variable to store generated captcha
let captchaText = null;

// Function to generate captcha
const generateCaptcha = () => {
  const randomString = Math.random().toString(36).substring(2, 7);
  const randomStringArray = randomString.split("");
  const changeString = randomStringArray.map((char) => (Math.random() > 0.5 ? char.toUpperCase() : char));
  captchaText = changeString.join("   ");
  captchaTextBox.value = captchaText;
  console.log(captchaText);
};

const refreshBtnClick = () => {
  generateCaptcha();
  captchaInputBox.value = "";
  captchaKeyUpValidate();
};

const captchaKeyUpValidate = () => {
  //Toggle submit button disable class based on captcha input field.
  submitButton.classList.toggle("disabled", !captchaInputBox.value);

  if (!captchaInputBox.value) message.classList.remove("active");
};

// Function to validate the entered captcha
const submitBtnClick = () => {
  captchaText = captchaText
    .split("")
    .filter((char) => char !== " ")
    .join("");
  message.classList.add("active");
  // Check if the entered captcha text is correct or not
  if (captchaInputBox.value === captchaText) {
    message.innerText = "Entered captcha is correct";
    message.style.color = "#826afb";
  } else {
    message.innerText = "Entered captcha is not correct";
    message.style.color = "#FF2525";
  }
};

// Add event listeners for the refresh button, captchaInputBox, submit button
refreshButton.addEventListener("click", refreshBtnClick);
captchaInputBox.addEventListener("keyup", captchaKeyUpValidate);
submitButton.addEventListener("click", submitBtnClick);

// Generate a captcha when the page loads
generateCaptcha();

We start by defining the characters that can appear in the CAPTCHA. The generateCaptcha function creates a random string of six characters and draws it on the canvas. The refreshButton allows users to generate a new CAPTCHA. The captchaForm validates the entered CAPTCHA text against the generated text, displaying appropriate messages.

Advertisement

By following these steps, you have created a simple CAPTCHA generator using HTML and CSS, enhanced with JavaScript. This CAPTCHA can help prevent automated bots from abusing your web forms. While this is a basic example, it provides a foundation for understanding how CAPTCHAs work and can be expanded with additional security features and improvements.

For real-world applications, consider using more robust CAPTCHA services like Google’s reCAPTCHA, which offers better security and user experience.