Open In App

How to make a QR Code generator using qrcode.js ?

Last Updated : 19 Dec, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

Modern web applications require generating QR codes for certain features where we need to enable a convenient way of data sharing like QR codes for the end users. Some popular QR codes use cases are UPI payment addresses, invoice details, contact cards, web links, etc. QR(Quick Response) code is a machine-readable matrix type of barcode that contains an array of black and white square grid, typically utilized to keep the URLs or other data for reading by the imaging systems, i.e. camera on a smartphone. QR code has faster readability and more storage capacity as compared to UPC barcodes. Now, the task is to create the QR Code generator with the help of qrcode.js, along with understanding the various ways to implement it through the illustrations.

QRCode.js is a popular open-source front-end easy-to-use javascript library that facilitates to create the QRCode. This library supports Cross-browser QR Code generation with HTML 5 canvas and table tag. QRCode.js doesn’t have any additional dependencies.

 Syntax: This library exposes a class named QRCode to us and the constructor expects two parameters as follows: 

new QRCode(Target,Options);

Parameter Values:

  • Target [string or HTML element] : This parameter specifies the string, which is the id or the element which we want to target for displaying the QR code. For instance,
new QRCode(document.getElementById("id-of-element"), "content of QR Code");
or
new QRCode("id-of-element", "content of QR code");
  • Options [string or JSON]: This parameter contains 2 options: 
    • string: For basic usage we can directly provide the content of QR code
    • JSON: When we need some customization
      • text [string]: content of QR code
      • width,height [int]: width and height of QR code
      • colorDark[string]: color of qr code
      • colorLight[string]: color of qr code background
      • correctlevel:  error correction level
new QRCode(document.getElementById("qrcode"), "content as string");
or
var qrcode = new QRCode("test", {
 text: "http://www.geeksforgeeks.org",
 width: 256,
 height: 256,
 colorDark : "#000000",
 colorLight : "#ffffff",
 correctLevel : QRCode.CorrectLevel.H
});

Approach: A QR code can be generated at the back end on the server and as well at the front end on the client side. This article will cover the client-side QR code generation.

Requirements or Dependencies: We can use/import the following libraries into the project in a 3 ways: 

  • Download the script file locally [Link]
  • Via CDN [Link]
  • Node package manager [Link]

Procedure to be followed for Generating QR Code:

  • Import the above-mentioned libraries to our project.
  • Decide the target location on the web page where we would like to display the QR code.
  • Create an element/container for QR Code at the target location and provide it an identifier like id.
  • Decide upon the appearance of the QR code and its content.
  • Create a QRCodejs object with a target and options.

Note: Below examples demonstrates the CDN link for importing the library.

Static QR code Generation: This is suitable when the content for the QR code is already available at the time of rendering the page and is not going the change by actions performed by the user. We place a <div> element that will contain a QR code. This <div> has an id for identification and can be placed at a suitable location in the body element as per the requirements. Then, we need to include a <script> tag where we initialize the QR code class object with the <div> element’s id and options as the QR code’s content.

Example 1: Here in this example, the content of the QR code is the link to GeeksforGeeks website.

HTML




<!DOCTYPE html>
<html lang="en">
 
<head>
    <meta charset="UTF-8" />
    <meta name="viewport"
         content="width=device-width,
                        initial-scale=1.0" />
    <title>QR Code Generator</title>
    
    <style>
        h1, h3 {
          color: green;
        }
        body, header {
          display: flex;
          flex-direction: column;
          justify-content: center;
          align-items: center;
        }
    </style>
    <script src=
    </script>
</head>
 
<body>
    <header>
        <h1>GeeksforGeeks</h1>
        <h3>QR code generator using qrcode.js</h3>
        <h3>To visit geeksforgeeks.org scan below code</h3>
    </header>
    <main>
        <div id="qrcode"></div>
    </main>
     
    <script>
        var qrcode = new QRCode("qrcode",
        "https://www.geeksforgeeks.org");
    </script>
</body>
 
</html>


Output

Static QR code generation example

Dynamic QR code Generation: This is suitable when the content of the QR code is not available at the time of rending the page and depends on actions performed by the user which should lead to the generation of a QR code on the fly. Here, similar to the previous example, we need to place the target <div> element with an id which will contain a QR code once it is generated. For the dynamic generation demonstration, the below example uses a form with an input element for receiving the QR code’s content from the user.

In the script, we mainly have 2 things, i.e. generateQrCode function & Form submission event listener. In generateQrCode function, this will accepts QR code content as a parameter and generates the QR code with the QR code’s target div element and options with content. Whereas, In Form submission event listener, once the form is submitted, first thing we do is prevent the submission event as we don’t want to send the request to any server. Then we check if the QRcode object is already available or not.

  • If not available then we generate the QRcode object using the generator function defined by us, which in turn also renders the QR code in the target <div> element.
  • If already available then use the existing object and use a method provided by the QRcode class that is makeCode which requires one parameter that is QR-code content and when invoked re-generates the QR code with updated content but with existing other options if provided previously.

Example 2: This example illustrate generating the Dynamic QR code using the QRCode.js.

HTML




<!DOCTYPE html>
<html lang="en">
 
<head>
    <meta charset="UTF-8" />
    <meta name="viewport"
          content="width=device-width,
                         initial-scale=1.0" />
    <title>QR Code Generator</title>
    <style>
        h1, h3 {
          color: green;
        }
        body, header {
          display: flex;
          flex-direction: column;
          justify-content: center;
          align-items: center;
        }
    </style>
 
    <script src=
    </script>
</head>
 
<body>
    <header>
        <h1>GeeksforGeeks</h1>
        <h3>QR code generator using qrcode.js</h3>
        <h3>Enter QR code content and generate QR</h3>
    </header>
    <main>
        <form action="/"
              id="qr-generation-form">
            <input type="text"
                   name="qr-code-content"
                   id="qr-content"
                   value=""
                   placeholder="Enter QR content"
                   autocomplete="off" />
            <input type="submit"
                   value="Generate QR Code" />
        </form><br />
        <div id="qr-code"></div>
    </main>
</body>
<script>
    let qrContentInput = document.getElementById("qr-content");
    let qrGenerationForm =
    document.getElementById("qr-generation-form");
    let qrCode;
     
    function generateQrCode(qrContent) {
      return new QRCode("qr-code", {
        text: qrContent,
        width: 256,
        height: 256,
        colorDark: "#000000",
        colorLight: "#ffffff",
        correctLevel: QRCode.CorrectLevel.H,
      });
    }
     
    // Event listener for form submit event
    qrGenerationForm.addEventListener("submit", function (event) {
      // Prevent form submission
      event.preventDefault();
      let qrContent = qrContentInput.value;
      if (qrCode == null) {
           
        // Generate code initially
        qrCode = generateQrCode(qrContent);
      } else {
           
        // If code already generated then make
        // again using same object
        qrCode.makeCode(qrContent);
      }
    });
</script>
 
</html>


Output

A dynamic QR code generator

Reference: Library Repository: https://github.com/davidshimjs/qrcodejs



Similar Reads

Create a QR code generator app using ReactJS
Introduction: In this article, we are going to make a simple QR Code generator app. QR code is a two-dimensional barcode readable on smartphones. Allows coding of more than 4000 characters in a double-barcode bar. QR codes can be used to show text to a user, to open a URL, to keep contact in an address book or to write messages. Prerequisites: The
3 min read
Barcode Code Generator using jQuery Plugin
In this article, we are going to generate the barcode for any text value using HTML, CSS, and Jquery. Barcode is the unique representation of the characters and numbers in the form of lines and space. It is widely used in stores and many places. Current day, you have seen the barcode on most of the products that are sold outs in the market. We can
5 min read
Create an QR Code Generator Project using HTML CSS & JavaScript
In today's digital world, QR codes are widely used and provide a practical way to share information and access content with a quick scan. This deeply manually operated will show you step-by-step how to create a QR code generator from scratch using HTML, CSS, and JavaScript. This article will give you the knowledge necessary to develop an intuitive
3 min read
Create a QR Code Generator App using React-Native
In this article, we will walk you through the process of building a QR Code Generator app using React Native. A QR Code Generator App is a mobile application that allows users to create QR codes from text or URLs. It generates QR codes, which can store information such as website links, contact details, or other data, for easy sharing and scanning
3 min read
YouTube Video Embed Code Generator Tool using HTML CSS and JavaScript
In this article, we will see How to create your own YouTube Video embed code generator tool using the basics of HTML, CSS, and JavaScript. With this tool, we can create responsive embed code for responsive video output on all devices. We can make use of this tool and add the generated code in Blogger, WordPress, Wix, Google Sites, custom websites,
4 min read
QR Code Generator using HTML, CSS and jQuery
In this article, we will learn how to build a QR generator using HTML, CSS, and jQuery. A QR code generator is an application that stores any required textual data into a QR code which can be later scanned with a QR code scanner to reveal the stored information. This code generator consists of an input field and a button which are respectively used
3 min read
Build a QR Code Generator Web App
A quick response code or QR code is a type of barcode in the form of a matrix. These are machine-readable optical labels that contain pieces of information about the items attached to them. In this article, we will be creating our own QR code generator from scratch using HTML, CSS, and JavaScript. We will try to generate a QR code by giving text in
5 min read
QR Code Generator Service with Node.js and Express.js
Nowadays, Quick Response (QR) codes have become an integral tool for transferring information quickly and conveniently. This project aims to develop a QR code generation API service using Node.js and Express.js. In addition, it goes further and extends the former by providing more customization options to follow RESTful API design principles and ha
5 min read
How to convert 3-digit color code to 6-digit color code using JavaScript ?
In this article, we are converting a three-digit color HEX code into a six-digit color HEX code using JavaScript. To solve this problem, first, we copy the individual digits and paste them at the consecutive positions. For example - #34E will be converted into #3344EE and #E90 will be converted into #EE9900. Steps to convert 3-digit color code to 6
2 min read
How to generate QR-Code using 'react-qr-code' in ReactJS ?
react-qr-code is a module or package for react that provides the QRCode component to generate the code with custom values. QR code is a square grid that can easily be readable with digital devices like smartphones. Syntax:&lt;QRCode title="title" value="value" bgColor="background-color" fgcolor="foreground-color" level="level" size={number}/&gt;Pro
2 min read