Leverage Turing Intelligence capabilities to integrate AI into your operations, enhance automation, and optimize cloud migration for scalable impact.
Advance foundation model research and improve LLM reasoning, coding, and multimodal capabilities with Turing AGI Advancement.
Access a global network of elite AI professionals through Turing Jobs—vetted experts ready to accelerate your AI initiatives.
Business owners and companies often require generating QR (quick response) codes for their websites. The demand for this effortless way of accessing websites is increasing and with the use of smartphones, users can easily scan a QR code and will be directed to the desired site. It’s not just websites that can be accessed either; QR codes can also be used to save sensitive information or data about a company.
In this article, we will look at generating QR codes with the help of a JavaScript QR code generator using QRCode.js and Tailwind CSS.
This is a library that allows you to create QR codes using JavaScript. QR codes are machine-readable codes consisting of an array of black and white squares used to store URLs or other information to be read by a camera or a smartphone. You don’t need to rely on external APIs or domain names when using a JavaScript QR code in a web application.
These QR code JavaScript libraries, which are open source, provide an API for generating QR codes with options like size, color, and correction level to suit your requirements.
Some popular JavaScript QR code generators include QRCode.js, QRious, and jsQR. We’ll be working with the QRcode.js library in this article.
As mentioned, QRCode.js is a JavaScript QR code library for making QR codes. It supports cross-browser with HTML5 Canvas and table tag in DOM. It has no dependencies.
The syntax collects two parameters, which are target and options.
Now that we’ve covered what JavaScript QR code means and what it’s used for, let’s look at what a QR code is composed of. We’ll use the QR code of the Turing website to list all the components.
This is the empty border around the QR code. The space enables the scanner to distinguish the QR code from the surrounding.
These are used to recognize the code and read it at a high speed, while indicating the direction in which the code is printed. It is located in the top right, top left, and bottom right corners.
This is a small square near the bottom right corner. The pattern allows the QR code to be detected even when it is slanted or not properly aligned.
The bigger the QR code (in size), the more alignment pattern it needs.
The decoder can calculate the width of the data matrix using these patterns. It is an L shape that runs around the detention pattern.
These patterns serve as data storage for data masking and error correction. The QR code may be read even if it is partially covered or broken, thanks to the error-correcting feature.
The QR code version is specified by these patterns. There are currently 40, with version 1 having 21 x 21 dots and version 40 having 177 x 177 dots.
This pattern preserves the real data included in the QR code.
Aside from the QRCode.js library, we will also use Tailwind and Vanilla JavaScript for this project.
1. Create an index.html file
Open VS Code or any code editor of your choice. Create an index.html file and enter the following code:
<!DOCTYPE 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" /> <meta name="author" content="Onwuemene Joshua" /> <title>Turing QR Code Generator</title> </head><script src="main.js" defer></script> <body>
</body> </html>
This file will hold all the HTML code as well as the Tailwind styling and JavaScript code.
Before using Tailwind CSS, you need to install it into the HTML file. There are three ways to do this:
We will be using Play CDN to install Tailwind CSS since ours is a simple project.
2. Install Play CDN and the HTML file
Input the following code to install Play CDN inside the head tag.
<script src="https://cdn.tailwindcss.com"></script>
We will be using a Google font called Poppins which will be added in the head tag and in the Tailwind config. The screen sizes are defined here: sm for small screens (min-width of 480px), md for medium screens (min-width of 768px), lg for large screens (min-width of 976px), and xl for extra large screens (min-width of 1440px).
<!DOCTYPE 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" /> <meta name="author" content="Onwuemene Joshua" /> <link rel="preconnect" href="https://fonts.googleapis.com" /> <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin /> <link href="https://fonts.googleapis.com/css2?family=Be+Vietnam+Pro:ital,wght@0,400;0,700;1,400&family=Fira+Code:wght@500;700&family=Fraunces:ital,opsz,wght@0,9..144,100;1,9..144,900&family=Outfit:wght@400;700&family=Poppins:wght@400;500;700&display=swap" rel="stylesheet" /> <script src="https://cdn.tailwindcss.com"></script> <script> tailwind.config = { theme: { extend: { fontFamily: { sans: ["Poppins", "monospace"], }, screens: { sm: "480px", md: "768px", lg: "976px", xl: "1440px", }, }, }, }; </script>
The final code will look like this in the HTML file.
<!DOCTYPE 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" /> <meta name="author" content="Onwuemene Joshua" /> <link rel="preconnect" href="https://fonts.googleapis.com" /> <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin /> <link href="https://fonts.googleapis.com/css2?family=Be+Vietnam+Pro:ital,wght@0,400;0,700;1,400&family=Fira+Code:wght@500;700&family=Fraunces:ital,opsz,wght@0,9..144,100;1,9..144,900&family=Outfit:wght@400;700&family=Poppins:wght@400;500;700&display=swap" rel="stylesheet" /> <script src="https://cdn.tailwindcss.com"></script> <script> tailwind.config = { theme: { extend: { fontFamily: { sans: ["Poppins", "monospace"], }, screens: { sm: "480px", md: "768px", lg: "976px", xl: "1440px", }, }, }, }; </script><script src="main.js" defer></script> <title>Turing QR Code Generator</title>
</head> <style> #qr-code { display: flex; align-items: center; justify-content: center; margin: 30px; padding: 33px 0; }
#Generate { background-color: #3498db; /* transition: height ease; */ padding: 20px; border-radius: 2rem; height: 300px; } @media screen and (max-width: 414px) { #Generate { height: 400px; } }
</style> <body> <main> <div class="flex flex-col-reverse align-center justify-content m-auto md:max-w-4xl md:flex-row mt-24 p-10" > <div id="Generate" class="w-full md:w-2/3 mr-24"> <h1 class="text-3xl font-bold mb-4 md:text-4xl text-center"> QR Code Generator </h1> <p class="mt-7">Enter your Url to generate your QR code</p>
<form id="Form" class="mt-4"> <input id="formData" type="text" placeholder="Enter your url" class="mr-3 focus:outline-none mb-5 rounded p-4 w-full border-2 border-gray-200" /> <button id="button" class="bg-gray-600 rounded-md p-4 w-full text-white" > Generate your QR code </button> </form> </div> <div class="w-full md:w-1/3 self-center"> <img src="Turing logo2.png" class="-mt-20 m-auto md:align-center" alt="Turing logo" /> </div> </div> <!-- Where the generated QR code will be. --> <div id="qr-code" class="m-auto"></div> </main>
</body> </html>
In our index.html file, we had an internal styling different from the Tailwind utility styling which was used to style the id label Generate for smaller screens. It was given a height of 400px when its screen size is 414px and below.
The output will be:
Note: Before using the QRCode.js library, you need to install it in the HTML file. To do this, go to cdnjs.com to search for its CDN and install its scripts tag.
Copy and paste the scripts tag in the head tag on your index.html file.
<script src="https://cdnjs.cloudflare.com/ajax/libs/qrcodejs/1.0.0/qrcode.min.js" integrity="sha512-CNgIRecGo7nphbeZ04Sc13ka07paqdeTu0WR1IM4kNcpmBAUSHSQX0FslNhTDadL4O5SAGapGt4FodqL8My0mA==" crossorigin="anonymous" referrerpolicy="no-referrer" ></script>
3. JavaScript file
In the main.js file, use the document.querySelector() method to select the form and the qr-code (the position you want the generated QR code to go).
const form = document.querySelector("#Form"); const qrCode = document.querySelector("#qr-code");
Create a generateSubmit function that holds most of the activities that will occur when you click on the form.
const generateSubmit = (e) => { };
Call on the e.preventDefault() on the form when it is clicked. e.preventDefault() stops the form from submitting. It is used when you are trying to get the value from a form and using the value to do something. In this case, you are using the value of the form to generate the QR code.
const generateSubmit = (e) => { e.preventDefault(); };
Create a variable which is used to get the value (what is typed) from a form. For example, when you type Turing and click on Generate your QR code, it should console.log Turing in the developer’s console.
const generateSubmit = (e) => { e.preventDefault(); const url = document.querySelector("#formData").value; console.log(url); };
You’ll use a conditional statement to validate the form. If the form is empty, alert Please enter a valid URL. If there is value in the form, generate the QR code for it.
const generateSubmit = (e) => { e.preventDefault(); const url = document.querySelector("#formData").value; console.log(url); //form validation if (url === "") { alert("please enter a valid url"); } else { generateQrCode(url); } };
4. Create a function that generates the QR code
To generate the QR code, take a look at the GitHub QRCode.js documentation.
const generateQrCode = (url) => { const qr = new QRCode(document.getElementById("qr-code"), { text: url, width: 300, height: 300, }); };
5. Clear the QR code
Although we’ve created the QR code, the app will not clear it and will instead append the new generated QR code to the previously generated one.
To resolve this, clear the previous QR code when you want to create a new one by using innerHTML and setting it to an empty string.
const clearQR = () => { qrCode.innerHTML = ""; };
6. Adding an event listener to the form
EventListener in JavaScript responds to user inputs and actions.
form.addEventListener("submit", generateSubmit);
The following shows the complete html.file:
<!DOCTYPE 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" /> <meta name="author" content="Onwuemene Joshua" /> <link rel="preconnect" href="https://fonts.googleapis.com" /> <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin /> <link href="https://fonts.googleapis.com/css2?family=Be+Vietnam+Pro:ital,wght@0,400;0,700;1,400&family=Fira+Code:wght@500;700&family=Fraunces:ital,opsz,wght@0,9..144,100;1,9..144,900&family=Outfit:wght@400;700&family=Poppins:wght@400;500;700&display=swap" rel="stylesheet" /> <script src="https://cdn.tailwindcss.com"></script> <script> tailwind.config = { theme: { extend: { fontFamily: { sans: ["Poppins", "monospace"], }, screens: { sm: "480px", md: "768px", lg: "976px", xl: "1440px", }, }, }, }; </script> <script src="https://cdnjs.cloudflare.com/ajax/libs/qrcodejs/1.0.0/qrcode.min.js" integrity="sha512-CNgIRecGo7nphbeZ04Sc13ka07paqdeTu0WR1IM4kNcpmBAUSHSQX0FslNhTDadL4O5SAGapGt4FodqL8My0mA==" crossorigin="anonymous" referrerpolicy="no-referrer" ></script> <script src="main.js" defer></script> <title>Turing QR Code Generator</title> </head> <style> #qr-code { display: flex; align-items: center; justify-content: center; margin: 30px; padding: 33px 0; }#Generate { background-color: #3498db; /* transition: height ease; */ padding: 20px; border-radius: 2rem; height: 300px; } @media screen and (max-width: 414px) { #Generate { height: 400px; } }
</style> <body> <main> <div class="flex flex-col-reverse align-center justify-content m-auto md:max-w-4xl md:flex-row mt-24 p-10" > <div id="Generate" class="w-full md:w-2/3 mr-24"> <h1 class="text-3xl font-bold mb-4 md:text-4xl text-center"> QR Code Generator </h1> <p class="mt-7">Enter your Url to generate your QR code</p>
<form id="Form" class="mt-4"> <input id="formData" type="text" placeholder="Enter your url" class="mr-3 focus:outline-none mb-5 rounded p-4 w-full border-2 border-gray-200" /> <button id="button" class="bg-gray-600 rounded-md p-4 w-full text-white" > Generate your QR code </button> </form> </div> <div class="w-full md:w-1/3 self-center"> <img src="Turing logo2.png" class="-mt-20 m-auto md:align-center" alt="Turing logo" /> </div> </div> <!-- Where the generated QR code will be. --> <div id="qr-code" class="m-auto"></div> </main>
</body> </html>
The following shows the complete main.js file:
const form = document.querySelector("#Form"); const qrCode = document.querySelector("#qr-code");const generateSubmit = (e) => { e.preventDefault(); clearQR();
const url = document.querySelector("#formData").value; console.log(url);
//form validation if (url === "") { alert("please enter a valid url"); } else { generateQrCode(url); } };
const generateQrCode = (url) => { const qr = new QRCode(document.getElementById("qr-code"), { text: url, width: 300, height: 300, }); };
const clearQR = () => { qrCode.innerHTML = ""; };
form.addEventListener("submit", generateSubmit);
Here is the final solution of the project.
We’ve explored QR code in JavaScript, the library used, the components of a QR code, and how to create one using a JavaScript QR code generator. By following a few broad guidelines, you can easily create one yourself:
Joshua is a frontend developer, a WordPress developer and a Technical writer. He has collaborated on projects which required his Html, CSS/SASS, TailwindCSS and JavaScript skills. He writes on frontend development explaining difficult concepts in a beginner-friendly manner.