FOR DEVELOPERS

How to Create a QR Code Using JavaScript

Create a QR Code Using JavaScript

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.

What is a JavaScript QR code generator?

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.

A brief overview of QRCode.Js

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.

  • Target: This parameter specifies the ID that it wants to target to display the QR code.
  • Option: This parameter is used to determine how you want the QR code to be, i.e., the size (height and width), color (color of the QR code), and correction level. This last is the extent to which data can be restored if the code is damaged. The greatest correction level is H, which can survive significant QR code damage.

Components of a QR code

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.

Component of a QR code.webp

Quiet zone

This is the empty border around the QR code. The space enables the scanner to distinguish the QR code from the surrounding.

create QR code.webp

Detention marker or position marker

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.

Generate QR Code Using JavaScript.webp

Alignment pattern

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.

JavaScript QR Code Generator.webp

The bigger the QR code (in size), the more alignment pattern it needs.

Timing pattern

The decoder can calculate the width of the data matrix using these patterns. It is an L shape that runs around the detention pattern.

QR Code Generator with JavaScript.webp

Format 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.

Build a QR Code Generator Using JavaScript.webp

Version information

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.

QR code generation.webp

Data and error correction keys

This pattern preserves the real data included in the QR code.

QR code Generator in JavaScript.webp

How to make a QR code

Aside from the QRCode.js library, we will also use Tailwind and Vanilla JavaScript for this project.

How to make a QR code.webp

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:

  • By using Tailwind CLI
  • By using PostCSS
  • By using Play CDN.

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&quot;&gt;&lt;/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&amp;family=Fira+Code:wght@500;700&amp;family=Fraunces:ital,opsz,wght@0,9..144,100;1,9..144,900&amp;family=Outfit:wght@400;700&amp;family=Poppins:wght@400;500;700&amp;display=swap"
rel="stylesheet"
/>
<script src="https://cdn.tailwindcss.com&quot;&gt;&lt;/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&amp;family=Fira+Code:wght@500;700&amp;family=Fraunces:ital,opsz,wght@0,9..144,100;1,9..144,900&amp;family=Outfit:wght@400;700&amp;family=Poppins:wght@400;500;700&amp;display=swap"
rel="stylesheet"
/>
<script src="https://cdn.tailwindcss.com&quot;&gt;&lt;/script>
<script>
tailwind.config = {
theme: {
extend: {
fontFamily: {
sans: ["Poppins", "monospace"],
},
screens: {
sm: "480px",
md: "768px",
lg: "976px",
xl: "1440px",
},
},
},
};
</script>

&lt;script src=&quot;main.js&quot; defer&gt;&lt;/script&gt;
&lt;title&gt;Turing QR Code Generator&lt;/title&gt;

</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>

      &lt;form id=&quot;Form&quot; class=&quot;mt-4&quot;&gt;
        &lt;input
          id=&quot;formData&quot;
          type=&quot;text&quot;
          placeholder=&quot;Enter your url&quot;
          class=&quot;mr-3 focus:outline-none mb-5 rounded p-4 w-full border-2 border-gray-200&quot;
        /&gt;


        &lt;button
          id=&quot;button&quot;
          class=&quot;bg-gray-600 rounded-md p-4 w-full text-white&quot;
        &gt;
          Generate your QR code
        &lt;/button&gt;
      &lt;/form&gt;
    &lt;/div&gt;
    &lt;div class=&quot;w-full md:w-1/3 self-center&quot;&gt;
      &lt;img
        src=&quot;Turing logo2.png&quot;
        class=&quot;-mt-20 m-auto md:align-center&quot;
        alt=&quot;Turing logo&quot;
      /&gt;
    &lt;/div&gt;
  &lt;/div&gt;
  &lt;!-- Where the generated QR code will be. --&gt;
  &lt;div id=&quot;qr-code&quot; class=&quot;m-auto&quot;&gt;&lt;/div&gt;
&lt;/main&gt;

</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:

How to make a QR code.webp

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.

qr code javascript library.webp

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.

  • Create a function and give a parameter which will hold the URL of the website you will create.
  • Give it a target which will hold where you want the QR code to display.
  • Give it a text which will hold the URL.
  • Give it a size, color, and correction level. These are optional.
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.

  • You select what you want to add an event listener on (form).
  • The event type (submit).
  • The code to run (generateSubmit).
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&amp;family=Fira+Code:wght@500;700&amp;family=Fraunces:ital,opsz,wght@0,9..144,100;1,9..144,900&amp;family=Outfit:wght@400;700&amp;family=Poppins:wght@400;500;700&amp;display=swap"
rel="stylesheet"
/>
<script src="https://cdn.tailwindcss.com&quot;&gt;&lt;/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>

      &lt;form id=&quot;Form&quot; class=&quot;mt-4&quot;&gt;
        &lt;input
          id=&quot;formData&quot;
          type=&quot;text&quot;
          placeholder=&quot;Enter your url&quot;
          class=&quot;mr-3 focus:outline-none mb-5 rounded p-4 w-full border-2 border-gray-200&quot;
        /&gt;

        &lt;button
          id=&quot;button&quot;
          class=&quot;bg-gray-600 rounded-md p-4 w-full text-white&quot;
        &gt;
          Generate your QR code
        &lt;/button&gt;
      &lt;/form&gt;
    &lt;/div&gt;
    &lt;div class=&quot;w-full md:w-1/3 self-center&quot;&gt;
      &lt;img
        src=&quot;Turing logo2.png&quot;
        class=&quot;-mt-20 m-auto md:align-center&quot;
        alt=&quot;Turing logo&quot;
      /&gt;
    &lt;/div&gt;
  &lt;/div&gt;
  &lt;!-- Where the generated QR code will be. --&gt;
  &lt;div id=&quot;qr-code&quot; class=&quot;m-auto&quot;&gt;&lt;/div&gt;
&lt;/main&gt;

</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.

Conclusion

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:

  1. Determine your objective in terms of what data you want the QR code to hold.
  2. Use a preferred library.
  3. Customize the QR code.
  4. Test and validate it.
  5. Download and distribute it to users.

Author

  • How to Create a QR Code Using JavaScript

    Onwuemene Joshua

    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.

Frequently Asked Questions

A barcode stores data in one dimension (can be read horizontally) whereas a QR code can store data in two dimensions (can be read horizontally and vertically).

A QR code scanner app can be used to scan QR codes on a smartphone or tablet. To scan, follow the steps below.

  • Download a QR code reader from the app store.
  • Open the app and aim your device’s camera at the QR code to scan it.
  • The QR code will be instantly recognized by the scanning app which will then show the data contained in it.

You can scan QR codes on some smartphones without downloading a third-party app. Just launch the camera app and aim it at the QR code to scan it. Other devices like digital cameras and barcode scanners can also read QR codes.

In addition to text and links, QR codes can hold vCard data, calendar events, wi-fi network information, phone numbers, email addresses, and more. A QR code's capacity for data storage is influenced by its size, complexity, and the type of data being stored.

In general, QR codes can store up to 2,953 bytes of binary data, 4,296 alphanumeric characters, or 7,089 numeric characters. The capacity can change depending on the capabilities of the scanner app and the QR code generator being used.

View more FAQs
Press

Press

What’s up with Turing? Get the latest news about us here.
Blog

Blog

Know more about remote work. Checkout our blog here.
Contact

Contact

Have any questions? We’d love to hear from you.

Hire remote developers

Tell us the skills you need and we'll find the best developer for you in days, not weeks.