How to Generate QR Codes Using CSS, JavaScript, and HTML

Introduction

Generating QR codes is a common requirement for many web applications. In this tutorial, we will explore how to create QR codes using HTML, CSS, and JavaScript. This approach allows you to generate QR codes dynamically on your web pages without relying on server-side code. We will use a JavaScript library called qrcode.js to simplify the QR code generation process. Additionally, we will cover various customization options and explain where to find the necessary library.

Required Tools and Techniques

To generate QR codes on a webpage, we will use:

  • HTML to structure the webpage.
  • CSS to style the QR code container.
  • JavaScript to generate and manipulate the QR codes using the qrcode.js library.

Full Code Snippet with Detailed Explanation

Here is the complete code snippet for generating QR codes, along with detailed comments and explanations for each part:

HTML

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>QR Code Generator</title>
    <!-- Link to the CSS file for styling -->
    <link rel="stylesheet" href="styles.css">
</head>
<body>
    <!-- Container for the QR code -->
    <div id="qr-code-container">
        <!-- Div where the QR code will be generated -->
        <div id="qrcode"></div>
    </div>
    <!-- Input field for user to enter the text for QR code generation -->
    <input type="text" id="qr-input" placeholder="Enter text to generate QR Code">
    <!-- Button to trigger the QR code generation -->
    <button onclick="generateQRCode()">Generate QR Code</button>
    <!-- Include the qrcode.js library -->
    <script src="qrcode.min.js"></script>
    <!-- Include the custom script file -->
    <script src="script.js"></script>
</body>
</html>

CSS (styles.css)

/* Style for the QR code container */
#qr-code-container {
    display: flex;
    justify-content: center;
    align-items: center;
    height: 300px;
    width: 300px;
    margin: 20px auto;
    border: 2px solid #000;
}

/* Style for the input field */
#qr-input {
    display: block;
    margin: 20px auto;
    width: 80%;
    padding: 10px;
    font-size: 16px;
}

/* Style for the button */
button {
    display: block;
    margin: 0 auto;
    padding: 10px 20px;
    font-size: 16px;
    cursor: pointer;
}

JavaScript (script.js)

// Function to generate the QR code
function generateQRCode() {
    // Get the text from the input field
    var qrText = document.getElementById("qr-input").value;

    // Clear any existing QR code from the container
    document.getElementById("qrcode").innerHTML = "";

    // Generate a new QR code with the specified text
    new QRCode(document.getElementById("qrcode"), {
        text: qrText,
        width: 300, // Width of the QR code
        height: 300, // Height of the QR code
        colorDark: "#000000",  // Default color for the QR code
        colorLight: "#ffffff", // Default background color for the QR code
        correctLevel: QRCode.CorrectLevel.H  // High level of error correction
    });
}

Step-by-Step Explanation

HTML Structure:

    • We start with a basic HTML structure, including a title and a link to our CSS file.
    • A div with the id qr-code-container will hold the generated QR code.
    • An input field with the id qr-input allows users to enter the text that will be encoded in the QR code.
    • A button is provided to trigger the QR code generation.
    • The qrcode.min.js library is included to handle the QR code generation.

    CSS Styling:

      • The #qr-code-container is styled to be a centered box with a fixed size. This ensures the QR code is displayed in a defined area on the page.
      • The #qr-input is styled to be responsive and centered, making it user-friendly.
      • The button is also styled for better user interaction, with padding and a cursor change on hover.

      JavaScript Function:

        • The generateQRCode function fetches the text from the input field when the button is clicked.
        • It then clears any existing QR code from the #qrcode div to prevent overlapping QR codes.
        • Using the QRCode class from the qrcode.min.js library, it generates a new QR code with the specified text. The function also includes options for setting the color and error correction level of the QR code.

        Customization Options

        You can customize the QR code in various ways to better suit your needs. Below are some additional customization options:

        Change QR Code Size

        You can adjust the size of the QR code by modifying the width and height properties.

        // Function to generate the QR code with custom size
        function generateCustomSizeQRCode() {
            var qrText = document.getElementById("qr-input").value;
            document.getElementById("qrcode").innerHTML = "";
            new QRCode(document.getElementById("qrcode"), {
                text: qrText,
                width: 500, // Custom width for the QR code
                height: 500, // Custom height for the QR code
                colorDark: "#000000",
                colorLight: "#ffffff",
                correctLevel: QRCode.CorrectLevel.H
            });
        }

        Customize QR Code Colors

        You can change the color of the QR code and its background by setting the colorDark and colorLight properties.

        // Function to generate the QR code with custom colors
        function generateCustomColorQRCode() {
            var qrText = document.getElementById("qr-input").value;
            document.getElementById("qrcode").innerHTML = "";
            new QRCode(document.getElementById("qrcode"), {
                text: qrText,
                width: 300,
                height: 300,
                colorDark: "#ff0000",  // Red color for the QR code
                colorLight: "#0000ff", // Blue background for the QR code
                correctLevel: QRCode.CorrectLevel.H
            });
        }

        Adjust Error Correction Level

        The error correction level determines how much of the QR code can be obscured while still being readable. You can set it to L, M, Q, or H.

        // Function to generate the QR code with custom error correction level
        function generateCustomErrorCorrectionQRCode() {
            var qrText = document.getElementById("qr-input").value;
            document.getElementById("qrcode").innerHTML = "";
            new QRCode(document.getElementById("qrcode"), {
                text: qrText,
                width: 300,
                height: 300,
                colorDark: "#000000",
                colorLight: "#ffffff",
                correctLevel: QRCode.CorrectLevel.L  // Low level of error correction
            });
        }

        Finding the qrcode.js Library

        You can find the qrcode.js library on GitHub. To include it in your project, download the qrcode.min.js file and place it in your project directory. Then, link it in your HTML file as shown in the example above. This library simplifies the process of generating QR codes with various customization options.

        Practical Usage

        This setup is ideal for scenarios where you need to generate QR codes dynamically based on user input. For example, it can be used in contact forms, event registration pages, or any application where you need to provide quick access to information via QR codes. The ability to customize the appearance and error correction level of the QR codes makes it versatile for different use cases.

        Related Subject

        Using QR Codes in Marketing:

          • Understand the role of QR codes in digital and print marketing strategies.
          • Source: QR Codes in Marketing

          Conclusion

          In this tutorial, we have demonstrated how to generate QR codes using HTML, CSS, and JavaScript. By following these steps, you can easily integrate QR code generation into your web applications. Feel free to experiment with the styles and functionalities to meet your specific needs. The ability to customize QR codes enhances their usefulness, making them suitable for a wide range of applications. If you have any questions or need further assistance, please leave a comment below.