How to Create Dynamic QR Codes with JavaScript

In this article I’ll explain how to Create Dynamic QR Codes with JavaScript.
Dynamic QR code generation in JavaScript can be achieved using libraries like qrcode.js or qrcode-generator. Below is a step-by-step guide on how to generate a QR code dynamically.

1.  Using qrcode.js (Lightweight & Simple)

First, add the qrcode.min.js library to your project. Then, create a container for the QR code and add the JavaScript to generate it:

<script src="https://cdnjs.cloudflare.com/ajax/libs/qrcodejs/1.0.0/qrcode.min.js"></script>

<div id="qrcode"></div>

<script>
  var qrCode = new QRCode(document.getElementById("qrcode"), {
    text: "https://example.com", // Dynamic text or URL
    width: 150,
    height: 150,
    colorDark: "#000000",
    colorLight: "#ffffff",
    correctLevel: QRCode.CorrectLevel.H // Error correction level
  });
</script>

2. Using qrcode-generator (More Customization)

First, include the library. Then, use the following script to generate a QR code dynamically:

<script src="https://cdnjs.cloudflare.com/ajax/libs/qrcode-generator/1.4.4/qrcode.min.js"></script>

<div id="qrcode"></div>

<script>
  var qr = qrcode(0, 'M'); // Error correction level 'M'
  qr.addData("https://example.com"); // Add dynamic content
  qr.make();
  
  document.getElementById("qrcode").innerHTML = qr.createImgTag(4); // Scale factor
</script>

3. Generating QR Codes from User Input

To generate a QR code based on user input, use the following approach:

<input type="text" id="qrText" placeholder="Enter text or URL">
<button onclick="generateQRCode()">Generate QR Code</button>
<div id="qrcode"></div>

<script>
  function generateQRCode() {
    var text = document.getElementById("qrText").value;
    document.getElementById("qrcode").innerHTML = ""; // Clear previous QR code
    new QRCode(document.getElementById("qrcode"), {
      text: text,
      width: 150,
      height: 150
    });
  }
</script>

Bonus: Download the QR Code as an Image

To allow users to download the QR code:

<button onclick="downloadQRCode()">Download QR Code</button>

<script>
  function downloadQRCode() {
    var qrCanvas = document.querySelector("#qrcode canvas");
    var link = document.createElement("a");
    link.href = qrCanvas.toDataURL("image/png");
    link.download = "qrcode.png";
    link.click();
  }
</script>

Conclusion:

  • qrcode.js is great for simple implementations.
  • qrcode-generator offers more control
  •  You can make it dynamic with user input
  • Allow users to download the QR code for convenience

You may also like this:

Rate this post

Categorized in: