Generate QR Code Using JavaScript

Generate QR Code Using JavaScript

In this article, we will learn one of the easiest and simplest ways to create a QR Code with the help of JavaScript.

Firstly let's speak about QR codes. QR Code known as Quick Response Code is a two-dimensional barcode. QR contains machine-readable information which is attached to it.

Every QR generated has some information attached to it. whenever the QR is scanned we can extract that information.

To generate QR we will be using a qrcode.js library and to use it in our project we will use the CDN of the qrcode.js.

Script Tag for using qrcode.js

<script src="https://cdnjs.cloudflare.com/ajax/libs/qrcodejs/1.0.0/qrcode.min.js"integrity="sha512-CNgIRecGo7nphbeZ04Sc13ka07paqdeTu0WR1IM4kNcpmBAUSHSQX0FslNhTDadL4O5SAGapGt4FodqL8My0mA==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>

Let's start by creating a simple form with two fields, URL and Size of the QR Code. URL will be a text field and the size of the QR Code will be a dropdown also a button to create the QR.

<main class="section">
    <form id="qr-generator">
        <div style="display:flex;">
        <label for="" style="margin-right:8px">Url</label>
        <input type="text" name="url" id="url" placeholder="Enter a Url">
        </div>
        <div style="display:flex;margin-top:16px">
        <label for="" style="margin-right:8px; ">Size</label>
        <select id="size">
            <option value="100">100X100</option>
            <option value="200">200X200</option>
            <option value="300" selected>300X300</option>
            <option value="400">400X400</option>
            <option value="500">500X500</option>
            <option value="600">600X600</option>
            <option value="700">700X700</option>
        </select>
        </div>
        <button class="generatebutton" type="submit">Generate QR</button>
    </form>
    </main>

For Displaying the QR Code and having a button for saving the QR Code we will create a section. We will use JavaScript to add the QR Code Image for the URL and Size and generate the Save Image Button.

<section class="section qrsection">
  <div style="flex-direction:column;">
    <div  id="qrcode"></div>

    <div id="generated" style="margin-top:24px;"></div>
  </div>
</section>

I tried keeping a simple web page to make it visually simple.

* {
    font-family:'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;  
}
header {
    display: flex;
    justify-content: center;
}
.section {
    display: flex;
    justify-content: center;

}
.linkstyle{
    padding: 8px;
    background-color: rgb(10, 231, 239);
    border-radius: 4px;
    color:rgb(20, 20, 20);
    margin-top: 24px;
    margin-left: 100px;
}
.linkstyle:hover{
    background-color: rgb(25, 183, 181);
}
form {
    width: 300px;
    padding-top: 60px;
    padding-left: 30px;
    height: 200px;
    border-radius: 8px;
    background-color: rgb(165, 163, 10);
}
input {
    width: 200px;
    border-radius: 4px;
    height:24px;
    border-style: 1px solid;
}
select {
    width:200px;
    border-radius: 4px;
    height:24px;
    border-style: 1px solid;
}
.generatebutton {
    width:100px;
    margin-top: 40px;
    border-radius: 4px;
    border-style: none;
    background-color: rgb(10, 231, 239);
    color:rgb(20, 20, 20);
    height: 32px;
    cursor: pointer;
    float: right;
    margin-right: 24px;
}
.generatebutton:hover{
    background-color: rgb(25, 183, 181);
}
.qrsection {
    margin-top:24px;   
}

So next, let us start with adding the functionality for generating the QR using JavaScript. Before speaking about how we will implement. Let us speak about qrcode.js. qrcode.js is a JavaScript Library for simply generating QR Codes.

First Let us add start by adding an Event Listener for the form element. It will listen to the submit event inside the form and call the function

// Listening to submit event in the form and 
//calling GenerateSubmit function 
form.addEventListener('submit',GenerateSubmit);

In the below function, we are accessing the URL and size inputs and we are calling another function by passing the URL and size and calling a function to create a save image button.

While Generating the QR we will clear the QR code tag and remove the link stored in the button. Then we will create the QR Code using new QRCode function.

After creating the QR we will pass the source of the QR Code to the createSaveBtn function with all the properties.

// Accessing the form and qrcode element
const form=document.getElementById('qr-generator');
const qr=document.getElementById('qrcode');
// Function to clear the UI 
const clearUI=()=>{
    const savelink=document.getElementById('save-link');
    qr.innerHTML='';
/*Checking if the element save image is created and 
if created clear the ui */
    if(savelink){ 
        savelink.remove();
    }
}
/*Function to create the QR Code with mentioned text,
width and height */
const GenerateQR=(url,size)=>{
        clearUI()
        var qrcode = new QRCode("qrcode", {
            text: url,
            width: size,
            height: size,
            colorDark : "#000000",
            colorLight : "#ffffff",
            correctLevel : QRCode.CorrectLevel.H
        });
}
/* Function to access the data points and GenerateQR 
Function and then call create Create Save Button 
after a 1000 milli second */
const GenerateSubmit=(e)=>{
    e.preventDefault();
    const url=document.getElementById('url').value;
    const size=document.getElementById('size').value;
    if(url==""){
        alert("Please Provide a URL!!")
    }
    else{
        GenerateQR(url,size)
        setTimeout(()=>{
        // Access the image url of the qr generated     
        const SaveUrl=qr.querySelector('img').src;
        createSaveBtn(SaveUrl);
        },1000)
    }
}
const createSaveBtn= (SaveUrl)=>{
    // Creating a link tag 
    const link=document.createElement('a');
    /*Specifying the id ,download name ,
     Inner name and styling for the button*/
    link.id='save-link';
    link.href=SaveUrl;
    link.download='qrcode';
    link.innerHTML='Save Image'
    link.classList='linkstyle'
    // Appending the link created to generated element 
    document.getElementById('generated').appendChild(link)
}

Result:

The QR Code is generated for the entered URL and Size. The QR Code can be scanned and will be redirected to the URL provided. The QR Code generated can also be saved as an Image.

For the Complete Code click on the GitHub Link: https://github.com/VineethDShetty/Generate-QR-using-JavaScript

And That's a Wrap, Thanks for Reading!!

If enjoyed reading this article. Do Like, Comment down your views, and share this article with your friends. Follow me for more such articles.