qr code

How to create a simple QR Code generator

See the Pen dyGMpqj by zoneboy (@zoneboy) on CodePen.

Welcome back to another interesting tutorial. This is simple and straightforward. Generating qr Code using JavaScript is much easier than expected. The use of QRCode.js a JavaScript library makes this possible.


qr code html

The first thing is to write the html code of our QR Code generator. We need an input field where we type the text to be converted. Then a button that will trigger the QR code. The generated QR code will be displayed in the qrcode div.

qr code view

You can see the result of our html code there. The generate qrcode button won’t do anything now since we haven’t added functionality to it using JavaScript. This is the next thing to do.


qr code javascript

The first thing will be to import the library code, since we are using the QRCode.js javascript library. It is a minified code. Once imported, we can then work on it.

The button element is accessed using the document.getElementById(‘click’); code and assigned a variable name. This will let us modify the generate qr code button.

The other element we need to access is the text input var qrdata = document.getElementById(‘qrdata’);. This will let us grab anything that is inputted.

The next thing is assigning couple of features to the qrcode variable. The features includes new QRCode(document.getElementById(‘qrcode’). This creates an instance of the QRCode object type. It basically creates a blank JavaScript object and then sets the QRCode arguments to the new object which is qrcode.

Other objects attached to the qrcode variable includes the width, height, and colors of the qr Code. You can change the dark color to red or anything you want and also the white color.

The next thing is to write the function to generate the qr code. We have to grab the input value first with qrdata.value; and assign it to a variable named data then make the qr code with whatever text written in the input field qrcode.makeCode(data);.

qr code final

The last thing is to create an event listener on the generate button that triggers the generateQRCode btn.addEventListener(‘click’, generateQRCode);.

You can see the outcome below

Check out the code on codepen

Leave a Comment

Your email address will not be published. Required fields are marked *