Creating a Custom Captcha using Pure JavaScript Tutorial

In this tutorial, you can learn to create a Custom CAPTCHA using Pure JavaScript. This tutorial aims to provide students and beginners with a reference for learning to build a useful component and feature for web applications or websites. Here, I will be providing a simple web page script that demonstrates the creation of a simple custom CAPTCHA Generator and Checker.

What is CAPTCHA?

A CAPTCHA is an acronym for Completely Automated Public Turing test to tell Computers and Humans Apart. It is a challenge–response test used in computing to determine whether the user accessing the software or web application is human. Developers implement this to websites or web applications to prevent bots from accessing the site.

How to Create a Custom CAPTCHA using Pure JavaScript?

Creating a CAPTCHA can be easily achieved using JavaScript's built-in properties, methods, and APIs. We can simply create the CAPTCHA form using the HTML elements such as inputs and text fields and design the elements using some CSS properties. Then we can create a code in JS that generates 6 random characters that serve as the CAPTCHA code that the user must identify. Check out the simple web page scripts that I created and provided below to know more about how to create a Custom CAPTCHA using Pure JavaScript.

Sample Web Page

The scripts below result in a simple web application page that generated CAPTCHA. The CAPTCHA Code can be regenerated or changed by clicking the Refresh button beside the captcha image. The user enters the CAPTCHA input field to confirm it.

CAPTCHA Background

Here is the image that is used in the scripts below and serves as the CAPTCHA background to make the code a bit hard to identify.

CAPTCHA Background Image

Page Interface

Here is the HTML file script known as index.html. This file contains the elements of the web application page layout and CAPTCHA form.

  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <meta charset="UTF-8">
  4. <meta name="viewport" content="width=device-width, initial-scale=1.0">
  5. <title>Custom Captcha in JavaScript</title>
  6. <link rel="stylesheet" href="style.css">
  7. <link rel="preconnect" href="https://fonts.googleapis.com">
  8. <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
  9. <link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Material+Symbols+Outlined:opsz,wght,FILL,[email protected],100..700,0..1,-50..200" />
  10. </head>
  11. <div class="container">
  12. <header>Creating Captcha using Pure JS</header>
  13. <div class="captcha-area">
  14. <div class="captcha-img">
  15. <img src="captcha-bg.jpg" alt="Captcha BG">
  16. <span class="captcha-text-field"></span>
  17. </div>
  18. <button class="reload-btn"><span class="material-symbols-outlined">refresh</span></button>
  19. </div>
  20. <form action="#" class="chaptcha-input">
  21. <input type="text" placeholder="Enter captcha" maxlength="6" spellcheck="false" required>
  22. <button class="confirm-btn">Check</button>
  23. </form>
  24. <div class="msg-field"></div>
  25. </div>
  26. <script src="script.js"></script>
  27. </body>
  28. </html>

Stylesheet

Next, here is the CSS file script known as style.css. This file contains the stylesheet codes for the elements of the page and the page layout.

  1. @import url('https://fonts.googleapis.com/css2?family=Roboto+Mono:ital,wght@0,100;0,200;0,300;0,400;0,500;0,600;1,100;1,200;1,300;1,400;1,500;1,600&display=swap');
  2. *{
  3. margin: 0;
  4. padding: 0;
  5. box-sizing: border-box;
  6. font-family: 'Roboto Mono', monospace;
  7. }
  8. .material-symbols-outlined {
  9. font-variation-settings:
  10. 'FILL' 0,
  11. 'wght' 400,
  12. 'GRAD' 0,
  13. 'opsz' 48
  14. }
  15. ::selection{
  16. color: #fff;
  17. background: #4db2ec;
  18. }
  19. body{
  20. display: flex;
  21. align-items: center;
  22. justify-content: center;
  23. min-height: 100vh;
  24. background: #19376D;
  25. }
  26. .container{
  27. max-width: 485px;
  28. width: 100%;
  29. background: #fff;
  30. padding: 22px 30px 40px;
  31. border-radius: 10px;
  32. box-shadow: 8px 8px 8px rgba(0, 0, 0, 0.05);
  33. }
  34.  
  35. .container header{
  36. color: #19376D;
  37. font-size: 33px;
  38. font-weight: 500;
  39. text-align: center;
  40. }
  41. .container .captcha-area{
  42. display: flex;
  43. height: 65px;
  44. margin: 30px 0 20px;
  45. align-items: center;
  46. justify-content: space-between;
  47. }
  48. .captcha-area .captcha-img{
  49. height: 100%;
  50. width: 345px;
  51. user-select: none;
  52. background: #000;
  53. border-radius: 5px;
  54. position: relative;
  55. }
  56. .captcha-img img{
  57. width: 100%;
  58. height: 100%;
  59. object-fit: cover;
  60. border-radius: 5px;
  61. opacity: 0.95;
  62. }
  63. .captcha-img .captcha-text-field{
  64. position: absolute;
  65. left: 50%;
  66. top: 50%;
  67. width: 100%;
  68. color: #fff;
  69. font-size: 35px;
  70. text-align: center;
  71. letter-spacing: 10px;
  72. transform: translate(-50%, -50%);
  73. text-shadow: 0px 0px 1px #727272bd;
  74. font-family: 'Noto Serif', serif;
  75. }
  76. .container button{
  77. outline: none;
  78. border: none;
  79. color: #fff;
  80. cursor: pointer;
  81. background: #19376D;
  82. border-radius: 5px;
  83. transition: all 0.3s ease;
  84. }
  85. .container button:hover{
  86. background: #112750;
  87. }
  88. .container button span{
  89. font-size:2rem;
  90. }
  91. .captcha-area .reload-btn{
  92. width: 75px;
  93. height: 100%;
  94. font-size: 25px;
  95. }
  96. .captcha-area .reload-btn i{
  97. transition: transform 0.3s ease;
  98. }
  99. .captcha-area .reload-btn:hover i{
  100. transform: rotate(15deg);
  101. }
  102. .container .chaptcha-input{
  103. height: 60px;
  104. width: 100%;
  105. position: relative;
  106. }
  107. .chaptcha-input input{
  108. width: 100%;
  109. height: 100%;
  110. outline: none;
  111. padding-left: 20px;
  112. font-size: 20px;
  113. border-radius: 5px;
  114. border: 1px solid #bfbfbf;
  115. }
  116. .chaptcha-input input:is(:focus, :valid){
  117. padding-left: 19px;
  118. border: 2px solid #4db2ec;
  119. }
  120. .chaptcha-input input::placeholder{
  121. color: #bfbfbf;
  122. }
  123. .chaptcha-input .confirm-btn{
  124. position: absolute;
  125. right: 7px;
  126. top: 50%;
  127. font-size: 17px;
  128. height: 45px;
  129. padding: 0 20px;
  130. opacity: 0;
  131. pointer-events: none;
  132. transform: translateY(-50%);
  133. }
  134. .chaptcha-input input:valid + .confirm-btn{
  135. opacity: 1;
  136. pointer-events: auto;
  137. }
  138. .container .msg-field{
  139. display: none;
  140. font-size: 18px;
  141. text-align: center;
  142. margin: 20px 0 -5px;
  143. }
  144.  
  145. @media (max-width: 506px){
  146. body{
  147. padding: 0 10px;
  148. }
  149. .container{
  150. padding: 22px 25px 35px;
  151. }
  152. .container header{
  153. font-size: 25px;
  154. }
  155. .container .captcha-area{
  156. height: 60px;
  157. }
  158. .captcha-area .captcha-text-field{
  159. font-size: 28px;
  160. letter-spacing: 5px;
  161. }
  162. .captcha-area .reload-btn{
  163. width: 60px;
  164. margin-left: 5px;
  165. font-size: 20px;
  166. }
  167. .container .chaptcha-input{
  168. height: 55px;
  169. }
  170. .chaptcha-input .confirm-btn{
  171. height: 40px;
  172. }
  173. .container .msg-field{
  174. font-size: 15px;
  175. }
  176. .captcha-area .captcha-img{
  177. width: 250px;
  178. }
  179. }

JavaScript

Lastly, here is the JavaScript file script known as script.js. The file scripts contain the codes that make the CAPTCHA functional.

  1. /**
  2. * Element Selectors
  3. */
  4. const captchaTextField = document.querySelector(".captcha-text-field")
  5. const refreshBTN = document.querySelector(".reload-btn")
  6. const inputField = document.querySelector(".chaptcha-input input")
  7. const confirmBTN = document.querySelector(".confirm-btn")
  8. const msgField = document.querySelector(".msg-field")
  9.  
  10. // Characters for Generating Captcha
  11. let chars = 'ABCDEFGHIJKLMNOPQRSTUVWXDabcdefghijklmnopqrstuvwxyz1234567890';
  12. // converting characters to array
  13. let charArr = chars.split('');
  14.  
  15. function generateCaptcha(){
  16. //Generate Captcha Characters
  17. for (let i = 0; i < 6; i++) {
  18. let randomCharacter = charArr[Math.floor(Math.random() * charArr.length)];
  19. // Display generated captcah to textfield
  20. captchaTextField.innerText += ` ${randomCharacter}`;
  21. }
  22. }
  23. // Reset Captacha Content
  24. function resetCaptchaContent(){
  25. inputField.value = "";
  26. captchaTextField.innerText = "";
  27. msgField.style.display = "none";
  28. }
  29.  
  30. // Trigger Generate Captcha
  31. generateCaptcha();
  32.  
  33. // Regenerate Captcha Code or Characters
  34. refreshBTN.addEventListener("click", ()=>{
  35. resetCaptchaContent();
  36. generateCaptcha();
  37. });
  38.  
  39. // Confirm if entered captcah value matches the generated captcha
  40. confirmBTN.addEventListener("click", e =>{
  41. e.preventDefault();
  42. let inputVal = inputField.value;
  43. if(inputVal == captchaTextField.innerText.split(' ').join('')){
  44. msgField.style.color = "#7AA874";
  45. msgField.innerText = "Captcha Confirmed";
  46. // Reset Captcha Field After 3 secods
  47. setTimeout(()=>{
  48. resetCaptchaContent();
  49. generateCaptcha();
  50. }, 3000);
  51. }else{
  52. msgField.style.color = "#ED2B2A";
  53. msgField.innerText = "Entered Captcha Value does not matched. Please try again!";
  54. }
  55. msgField.style.display = "block";
  56. });
  57.  

Snapshots

Here are the snapshots of the overall result of the script I have provided above.

Page UI

Custom CAPTHA using Pure JavaScript

If entered the wrong CAPTCHA Value

Custom CAPTHA using Pure JavaScript

If entered the right CAPTCHA Value

Custom CAPTHA using Pure JavaScript

There you go! I have provided also the complete source code zip file of the web page scripts above on this site and it is free to download. Feel free to download or copy the source code and modify it to do experiments to enhance your programming capabilities.

That's it! I hope this Creating a Custom Captcha using Pure JavaScript Tutorial will help you with what you are looking for and will be useful for your current and future web application projects.

Explore more on this website for more Tutorials and Free Source Codes.

Happy Coding =)

Add new comment