Create a Secure Captcha Generator with HTML, CSS, and JavaScript

Faraz

By Faraz -

Learn how to build an effective Captcha Generator using HTML, CSS, and JavaScript. Enhance your web security with this step-by-step tutorial.


Create a Secure Captcha Generator with HTML, CSS, and JavaScript.jpg

Table of Contents

  1. Project Introduction
  2. HTML Code
  3. CSS Code
  4. JavaScript Code
  5. Conclusion
  6. Preview

Captcha generators are essential for ensuring that bots don't interfere with your website. They provide an extra layer of security by requiring users to complete a challenge. In this guide, we'll show you how to create one using HTML, CSS, and JavaScript.

Join My Telegram Channel to Download the Project Source Code: Click Here

Prerequisites:

Before starting this tutorial, you should have a basic understanding of HTML, CSS, and JavaScript. Additionally, you will need a code editor such as Visual Studio Code or Sublime Text to write and save your code.

Source Code

Step 1 (HTML Code):

To get started, we will first need to create a basic HTML file. In this file, we will include the main structure for our captcha generator.

After creating the files just paste the following codes into your file. Make sure to save your HTML document with a .html extension, so that it can be properly viewed in a web browser.

I'll explain each part of the code:

1. <!DOCTYPE html>: This is the document type declaration, which specifies that this is an HTML5 document.

2. <html lang="en">: This opening tag defines the beginning of an HTML document and specifies that the document is in English ("en").

3. <head>: The <head> element contains meta-information about the document, such as character encoding, title, and external resources like stylesheets and scripts.

  • <meta charset="UTF-8">: This meta tag specifies that the character encoding of the document is UTF-8, which is a widely used character encoding for displaying text on web pages.
  • <meta http-equiv="X-UA-Compatible" content="IE=edge">: This meta tag is used to specify how Internet Explorer should render the page. It instructs IE to use the latest rendering engine available.
  • <meta name="viewport" content="width=device-width, initial-scale=1.0">: This meta tag is often used for responsive design. It tells the browser to set the viewport width to the device's width and to start with an initial zoom scale of 1.0.
  • <title>Captcha Generator Concept</title>: This sets the title of the web page that appears in the browser's title bar or tab.
  • <link rel="stylesheet" href="styles.css">: This line links an external CSS stylesheet called "styles.css" to style the HTML content.

4. <body onload="generate()">: The <body> element defines the main content of the web page. The onload attribute is used to specify a JavaScript function (generate()) that should be executed when the page is loaded.

  • <div class="wrapper"></div>: This creates an empty <div> element with the class "wrapper," which can be used to structure and style the content.
  • <h2 id="status" style="color: #ee7e6a;"></h2>: This is an empty <h2> heading with the id attribute set to "status." It also has an inline style to set its text color to a specific shade of orange.
  • <div> and <input> elements: These create a pair of input elements. The first <input> is of type "text" and has the readonly attribute, meaning it can't be edited by the user. It has the id attribute "generated-captcha." The second <input> is also of type "text" and has the id attribute "entered-captcha." It includes a placeholder text that instructs the user to enter the captcha.
  • <button> elements: Two buttons are created. The first one has a type attribute set to "button" and an onclick attribute that calls a JavaScript function named "check()" when clicked. The text on the button says "check." The second button is similar, but it calls the "generate()" function and has the id attribute "gen." Its text is "Generate New."
  • <script src="script.js"></script>: This line includes an external JavaScript file called "script.js" in the web page. It is used for scripting and functionality on the page.

This is the basic structure of our captcha generator using HTML, and now we can move on to styling it using CSS.

Step 2 (CSS Code):

Once the basic HTML structure of the captcha generator is in place, the next step is to add styling to the generator using CSS.

Next, we will create our CSS file. In this file, we will use some basic CSS rules to create our generator.

Let's break down the styles applied to various elements:

1. body: These styles are applied to the entire webpage's body element.

  • display: flex;: This sets the display property of the body to flex, allowing for flexible layout.
  • justify-content: center;: Horizontally centers the content within the body.
  • height: 100vh;: Sets the height of the body to 100% of the viewport height, ensuring the body takes up the entire screen.
  • align-items: center;: Vertically centers the content within the body.
  • padding: 0;: Removes any padding around the body element.
  • margin: 0;: Removes any margin around the body element.
  • flex-direction: column;: Sets the main axis of the flex container to be vertical, making content stack vertically.
  • background-color: #ffffff;: Sets the background color of the body to white.
  • background-image: ...;: Sets a background image for the body using inline SVG data.

2. div: These styles are applied to all div elements on the page.

  • margin-bottom: 10px;: Adds a 10-pixel margin at the bottom of each div.

3. button: These styles are applied to all button elements on the page.

  • margin-bottom: 5px;: Adds a 5-pixel margin at the bottom of each button.
  • cursor: pointer;: Changes the cursor to a pointer when hovering over a button.

4. input: These styles are applied to all input elements on the page.

  • text-decoration: none;: Removes any text decoration (like underlining) from the text within the input element.

5. #generated-captcha: These styles are applied to an element with the ID "generated-captcha."

  • text-decoration: line-through;: Adds a line through the text content.
  • font-weight: bold;: Sets the text to have a bold font weight.
  • text-align: center;: Centers the text horizontally.
  • font-size: 20px;: Sets the font size to 20 pixels.
  • background-color: #ede7f6;: Sets the background color to a pale purple shade.
  • border-radius: 6px;: Rounds the corners with a 6-pixel radius.
  • border: none;: Removes the border around the element.
  • padding: 6px;: Adds 6 pixels of padding around the content.
  • outline: none;: Removes the outline when the element is focused.
  • color: #1d1d1d;: Sets the text color to a dark gray.

6. #entered-captcha: These styles are applied to an element with the ID "entered-captcha."

  • border: 2px solid #c5c7f7;: Adds a 2-pixel solid border with a light blue-gray color.
  • font-family: monospace;: Sets the font to a monospace (fixed-width) font.
  • outline: none;: Removes the outline when the element is focused.
  • border-radius: 6px;: Rounds the corners with a 6-pixel radius.
  • padding: 8px 15px;: Adds 8 pixels of padding vertically and 15 pixels horizontally.
  • font-size: 12px;: Sets the font size to 12 pixels.

7. #gen: These styles are applied to an element with the ID "gen."

  • background-color: #ee7e6a;: Sets the background color to a reddish-orange color.

8. .wrappr: These styles are applied to elements with the class "wrappr."

  • display: flex;: Sets the display property to flex.
  • flex-direction: column;: Sets the main axis to be vertical.
  • justify-content: center;: Centers content vertically.

This will give our captcha generator an upgraded presentation. Create a CSS file with the name of styles.css and paste the given codes into your CSS file. Remember that you must create a file with the .css extension.

body {
  display: flex;
  justify-content: center;
  height: 100vh;
  align-items: center;
  padding: 0;
  margin: 0;
  flex-direction: column;
  background-color: #ffffff;
  background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 1600 900'%3E%3Cdefs%3E%3ClinearGradient id='a' x1='0' x2='0' y1='1' y2='0' gradientTransform='rotate(264,0.5,0.5)'%3E%3Cstop offset='0' stop-color='%230FF'/%3E%3Cstop offset='1' stop-color='%23CF6'/%3E%3C/linearGradient%3E%3ClinearGradient id='b' x1='0' x2='0' y1='0' y2='1' gradientTransform='rotate(199,0.5,0.5)'%3E%3Cstop offset='0' stop-color='%23F00'/%3E%3Cstop offset='1' stop-color='%23FC0'/%3E%3C/linearGradient%3E%3C/defs%3E%3Cg fill='%23FFF' fill-opacity='0' stroke-miterlimit='10'%3E%3Cg stroke='url(%23a)' stroke-width='5.28'%3E%3Cpath transform='translate(-73.5 16.8) rotate(10.5 1409 581) scale(1.042)' d='M1409 581 1450.35 511 1490 581z'/%3E%3Ccircle stroke-width='1.7600000000000002' transform='translate(-42 42) rotate(12.6 800 450) scale(1.021)' cx='500' cy='100' r='40'/%3E%3Cpath transform='translate(37.8 -126) rotate(126 401 736) scale(1.021)' d='M400.86 735.5h-83.73c0-23.12 18.74-41.87 41.87-41.87S400.86 712.38 400.86 735.5z'/%3E%3C/g%3E%3Cg stroke='url(%23b)' stroke-width='1.6'%3E%3Cpath transform='translate(252 -16.8) rotate(4.2 150 345) scale(0.958)' d='M149.8 345.2 118.4 389.8 149.8 434.4 181.2 389.8z'/%3E%3Crect stroke-width='3.5200000000000005' transform='translate(-168 -105) rotate(151.2 1089 759)' x='1039' y='709' width='100' height='100'/%3E%3Cpath transform='translate(-252 84) rotate(25.2 1400 132)' d='M1426.8 132.4 1405.7 168.8 1363.7 168.8 1342.7 132.4 1363.7 96 1405.7 96z'/%3E%3C/g%3E%3C/g%3E%3C/svg%3E");
  background-attachment: fixed;
  background-size: cover;
}
div {
  margin-bottom: 10px;
}
button {
  margin-bottom: 5px;
  cursor: pointer;
}
input {
  text-decoration: none;
}
#generated-captcha {
  text-decoration: line-through;
  font-weight: bold;
  text-align: center;
  font-size: 20px;
  background-color: #ede7f6;
  border-radius: 6px;
  border: none;
  padding: 6px;
  outline: none;
  color: #1d1d1d;
}
#entered-captcha {
  border: 2px solid #c5c7f7;
  font-family: monospace;
  outline: none;
  border-radius: 6px;
  padding: 8px 15px;
  font-size: 12px;
}
button {
  border: none;
  padding: 8px 20px;
  border-radius: 6px;
  font-size: 14px;
  font-family: monospace;
  font-weight: bold;
  outline: none;
  background-color: #64f394;
}

#gen {
  background-color: #ee7e6a;
}
.wrappr {
  /* border: 1px solid red; */
  display: flex;
  flex-direction: column;
  /* align-items: center; */
  justify-content: center;
} 

Step 3 (JavaScript Code):

Finally, we need to create a function in JavaScript.

1. let captcha; declares a variable captcha which will be used to store the generated captcha.

2. let alphabets = "AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz"; creates a string alphabets containing both uppercase and lowercase letters of the English alphabet.

3. let status = document.getElementById('status'); fetches an HTML element with the ID "status" and stores it in the status variable. This element is typically used to display status messages.

4. status.innerText = "Captcha Generator"; sets the text content of the status element to "Captcha Generator".

5. The generate function is defined using an arrow function. When called, this function generates a random captcha and updates the web page with the generated captcha.

  • first is set to a random character from the alphabets string.
  • second, third, and sixth are set to random single-digit numbers.
  • fourth and fifth are set to random characters from the alphabets string.
  • captcha is composed of these random values converted to strings, and the generated captcha is stored in the captcha variable.
  • The values of the generated captcha are displayed in two input fields on the web page using document.getElementById to select the corresponding HTML elements.

6. The check function is defined to validate the entered captcha.

  • It retrieves the value entered by the user in the input field with the ID "entered-captcha."
  • It compares the user's input with the stored captcha.
  • If they match, the status message is updated to "Correct!!".
  • If they don't match, the status message is updated to "Try Again!!", and the input field is cleared.

Create a JavaScript file with the name script.js and paste the given codes into your JavaScript file and make sure it's linked properly to your HTML document so that the scripts are executed on the page. Remember, you’ve to create a file with .js extension.

let captcha;
let alphabets = "AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz";
let status = document.getElementById('status');
status.innerText = "Captcha Generator";

 generate = () => {
let first = alphabets[Math.floor(Math.random() * alphabets.length)];
let second = Math.floor(Math.random() * 10);
let third = Math.floor(Math.random() * 10);
let fourth = alphabets[Math.floor(Math.random() * alphabets.length)];
let fifth = alphabets[Math.floor(Math.random() * alphabets.length)];
let sixth = Math.floor(Math.random() * 10);
captcha = first.toString()+second.toString()+third.toString()+fourth.toString()+fifth.toString()+sixth.toString();
document.getElementById('generated-captcha').value = captcha;
document.getElementById("entered-captcha").value = '';
status.innerText = "Captcha Generator"
}

 check = () => {
let userValue = document.getElementById("entered-captcha").value;
if(userValue == captcha){
    status.innerText = "Correct!!"
}else{
    status.innerText = "Try Again!!"
    document.getElementById("entered-captcha").value = '';
}
}

Final Output:

Create a Secure Captcha Generator with HTML, CSS, and JavaScript.gif

Conclusion:

Sum up the importance of Captcha generators in web security and the convenience they bring to user verification. Encourage your readers to implement this valuable tool in their web development projects.

This structured blog post will guide you through the process of creating a Captcha Generator using HTML, CSS, and JavaScript, ensuring enhanced security and user verification on your website.

Code by: Sumanth

That’s a wrap!

I hope you enjoyed this post. Now, with these examples, you can create your own amazing page.

Did you like it? Let me know in the comments below 🔥 and you can support me by buying me a coffee

And don’t forget to sign up to our email newsletter so you can get useful content like this sent right to your inbox!

Thanks!
Faraz 😊

End of the article

Subscribe to my Newsletter

Get the latest posts delivered right to your inbox


Latest Post

Please allow ads on our site🥺