How to generate QR code using JavaScript

Hello guys in this tutorial we will create QR Code Generator using HTML CSS & Javascript

First we need to create two files index.html and style.css then we need to do code for it.

Step:1

Add below code inside index.html

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <title>JavaScript QR Code Generator</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta https-equiv="X-UA-Compatible" content="ie=edge" />
    <link rel="stylesheet" href="style.css" />
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
    <script src="https://cdnjs.cloudflare.com/ajax/libs/qrious/4.0.2/qrious.min.js"></script>
  </head>
  <body>
    <div class="QRWrapper">
      <div class="QRWrapperInner">
        <div class="QRfield">
          <input id="qr-text" type="text" placeholder="Text to generate QR code"/>
          <button class="qr-btn" onclick="generateQRCode()">Create QR Code</button>
        </div>
        <div class="qr-code-result">
          <p id="qr-result">This is deault QR code:</p>
          <canvas id="qr-code"></canvas>
        </div>
      </div>
    </div>

     <script>
          /* JS comes here */
          var qr;
          (function() {
                        qr = new QRious({
                        element: document.getElementById('qr-code'),
                        size: 200,
                        value: 'https://blog.stackfindover.com/'
                    });
                })();
                
                function generateQRCode() {
                    var qrtext = document.getElementById("qr-text").value;
                    document.getElementById("qr-result").innerHTML = "QR code for " + qrtext +":";
                    //alert(qrtext);
                    qr.set({
                        foreground: '#0f62fe',
                        size: 200,
                        value: qrtext
                    });
                }
        </script>
  </body>
</html>

Step:2

Then we need to add code for style.css which code i provide in below screen.

* {
  padding: 0;
  margin: 0;
  font-family: 'IBM Plex Sans', sans-serif;
}
.QRWrapper {
    display: flex;
    align-items: center;
    justify-content: center;
    height: 100vh;
}
input#qr-text {
    font-size: 18px;
    padding: 10px 20px;
    outline: 0;
    border: 1px solid #0f62fe;
    min-width: 320px;
}
button.qr-btn {
    background-color: #0f62fe;
    border: 1px solid transparent;
    color: #fff;
    cursor: pointer;
    padding: calc(.875rem - 3px) 60px calc(.875rem - 3px) 20px;
    display: block;
    transition: background-color 0.5s;
    font-size: 18px;
    width: 100%;
    text-align: left;
    outline: 0;
}
.QRWrapperInner {
    display: grid;
    row-gap: 50px;
    align-items: center;
    justify-content: center;
    text-align: center;
}

Output:

Leave a Comment