Drawing QR-Code on Browser in Javascript
1 min read

Drawing QR-Code on Browser in Javascript

Drawing QR-Code on Browser in Javascript

In my quest to make the pages of one site a bit more mobile-friendly, I've got the idea to provide a QR-Code for an unique identifier generated for users. This is part of a wizard and the end-product is:

QR Code in a wizard

QR Code in JavaScript

To reach this outcome, I've started by looking for a QR javascript snippet. There are lots, but two drew my attention:

I've finally settled on Lars Jung's one, just because the info page looked a bit better, and because it can render <div /> based code. Cool.

Making it work

Downloading the code from github directly is a no go, because the plugin doesn't actually include the rendering code. It contains just the JQuery wrapper. I've finally got everything from the download (zip). Once it's placed in the right location (assets, lib or whatever suits you), all you need to do is:

  1. PLace a HTML DIV tag where you want the code to show:

    <div id="qrcode" style="margin:0 auto; width:200px"></div>
    
  2. Load the plugin (after loading JQuery). I use django so I need something like:

    {% extends "miner-apply/base.html" %}
    {% load staticfiles i18n %}
    
    {% block javascript %}
        {{ block.super }}
        <script src="{% static 'js/qrcode.jquery-0.7.0.js' %}"></script>
    {% endblock %}
    
  3. Draw the code at the end:

    <script>
        // Build the QR code
        //
        var s = $('input.textInput').val();
    
        $('#qrcode').empty().qrcode({
            render:'div',
            text: s,
            fill: '#182028'
        });
    </script>
    

Now, when the page is loaded, a QR code is drawn representing the string present in the <input /> element.

HTH,