How do I use a QR code in HTML? | How to Add a QR Code to Your Website: A Practical Guide | 3 Method To Use QR Code In HTML

How to Add a QR Code to Your Website: A Practical Guide

QR codes have become a seamless bridge between the physical and digital worlds. Adding your website to a QR Code can help users quickly share your URL, connect to social media, or save contact information. Let's explore how to use QR codes in HTML.

Method 1: Simple And Fastest Way (Static And Dynamic)

This is the easiest method. You Can Use QR Service into image source in <img> tag. The Popular service for static websites is QR Server, QRKit, qrcode-generator.com, Google's Chart Tools (though officially deprecated, it still works reliably), or a similar service like QRickit.

How it Works:

You construct a URL with parameters that define the data (like your website's URL) and size of the QR Code image You then use This URL as a src for your website.

Code Example:

<!DOCTYPE html>
<html>
<head>
    <title>My Website with QR Code</title>
</head>
<body>
    <h1>Scan to Visit Our Site!</h1>

    <!-- Example using a service like goqr.me -->
    <img src="https://api.qrserver.com/v1/create-qr-code/?size=150x150&data=https://www.programmingmacro.com"
         alt="QR Code linking to the homepage of Programming Macro Blog"
         title="Share Our Site" />

    <p>Scan this QR code with your phone to quickly visit our homepage.</p>
</body>
</html>

Breakdown of the URL:

  • https://api.qrserver.com/v1/create-qr-code/: The API endpoint.
  • ?size=150x150: This is Primary Parameter Start Here. This sets the QR Code image size to 150x150 pixels.
  • &data=https://...: This is the most important part, This Parameter Tells encodes the data into qr code

Pros:

  • Extremely easy to implement. No JavaScript or backend needed.
  • No need to generate and host an image file yourself.

Cons:

  • You rely on a third-party service. If it goes down, your QR code breaks.
  • Less control over advanced design features (like colors, inner logos).

Method 2: Dynamic QR Code Generation



For more control like custom styling and avoid third-party dependencies, and Online QR Code API Service Provider Use javascript library like qrcode.js. Documentation URL: https://davidshimjs.github.io/qrcodejs/

Step-by-Step Guide:

1. Include the Library: Add this library into your HTML file by including library it via a CDN (Content Delivery Network) without import Keyword in the JavaScript file.

<script src="https://cdn.jsdelivr.net/npm/qrcode@1.5.1/build/qrcode.min.js"></script>

2. Create a Canvas Element: This Is Where the QR Code will be Drawn During QR Code Generation

<canvas id="qrCode"></canvas>

3. Generate the QR Code with JavaScript: Use the API to render the QR code into the canvas element.

<script>
    // Select the canvas element
    const canvas = document.getElementById("qrCode");

    // Use the QRCode.toCanvas method
    QRCode.toCanvas(canvas, "https://www.yourawesomeblog.com", function (error) {
        if (error) console.error(error);
        console.log("QR code created successfully!");
    });
</script>

Full Example:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Advanced QR Code Generator</title>
    <script src="https://cdn.jsdelivr.net/npm/qrcode@1.5.1/build/qrcode.min.js"></script>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
        }
        
        body {
            background: linear-gradient(135deg, #6a11cb 0%, #2575fc 100%);
            min-height: 100vh;
            display: flex;
            justify-content: center;
            align-items: center;
            padding: 20px;
        }
        
        .container {
            background-color: rgba(255, 255, 255, 0.9);
            border-radius: 20px;
            box-shadow: 0 15px 30px rgba(0, 0, 0, 0.2);
            width: 90%;
            max-width: 500px;
            padding: 30px;
            text-align: center;
        }
        
        h1 {
            color: #333;
            margin-bottom: 20px;
            font-weight: 600;
            font-size: 28px;
        }
        
        .description {
            color: #666;
            margin-bottom: 25px;
            line-height: 1.5;
        }
        
        .input-group {
            margin-bottom: 20px;
            text-align: left;
        }
        
        label {
            display: block;
            margin-bottom: 8px;
            font-weight: 500;
            color: #444;
        }
        
        input[type="text"] {
            width: 100%;
            padding: 15px;
            border: 2px solid #ddd;
            border-radius: 10px;
            font-size: 16px;
            transition: border-color 0.3s;
        }
        
        input[type="text"]:focus {
            border-color: #4285f4;
            outline: none;
        }
        
        .buttons {
            display: flex;
            gap: 15px;
            margin-bottom: 25px;
        }
        
        button {
            flex: 1;
            padding: 15px;
            border: none;
            border-radius: 10px;
            font-size: 16px;
            font-weight: 600;
            cursor: pointer;
            transition: all 0.3s;
            display: flex;
            justify-content: center;
            align-items: center;
            gap: 8px;
        }
        
        #BTNGenerate {
            background-color: #4285f4;
            color: white;
        }
        
        #BTNGenerate:hover {
            background-color: #3367d6;
        }
        
        #BTNDownload {
            background-color: #0f9d58;
            color: white;
        }
        
        #BTNDownload:hover {
            background-color: #0b8046;
        }
        
        #BTNDownload:disabled {
            background-color: #cccccc;
            cursor: not-allowed;
        }
        
        .qr-container {
            margin: 20px 0;
            padding: 15px;
            background-color: white;
            border-radius: 10px;
            box-shadow: 0 5px 15px rgba(0, 0, 0, 0.05);
        }
        
        #qrCode {
            margin: 0 auto;
            display: block;
            border: 1px solid #eee;
            max-width: 100%;
        }
        
        .error {
            color: #ea4335;
            margin-top: 10px;
            font-weight: 500;
            display: none;
        }
        
        .success {
            color: #0f9d58;
            margin-top: 10px;
            font-weight: 500;
            display: none;
        }
        
        .footer {
            margin-top: 25px;
            color: #888;
            font-size: 14px;
        }
        
        @media (max-width: 600px) {
            .buttons {
                flex-direction: column;
            }
            
            h1 {
                font-size: 24px;
            }
            
            .container {
                padding: 20px;
            }
        }
    </style>
</head>
<body>
    <div class="container">
        <h1><i class="fas fa-qrcode"></i> QR Code Generator</h1>
        <p class="description">Generate custom QR codes for URLs, text, or contact information. Perfect for sharing websites, Wi-Fi access, or promotions.</p>
        
        <div class="input-group">
            <label for="urlInput">Enter URL or Text:</label>
            <input type="text" id="urlInput" placeholder="https://example.com" value="https://www.example.com">
        </div>
        
        <div class="buttons">
            <button id="BTNGenerate">
                <i class="fas fa-bolt"></i> Generate QR Code
            </button>
            <button id="BTNDownload" disabled>
                <i class="fas fa-download"></i> Download
            </button>
        </div>
        
        <div class="error" id="errorMessage">
            <i class="fas fa-exclamation-circle"></i> Please enter a valid URL or text!
        </div>
        
        <div class="success" id="successMessage">
            <i class="fas fa-check-circle"></i> QR Code generated successfully!
        </div>
        
        <div class="qr-container">
            <canvas id="qrCode"></canvas>
        </div>
        
        <div class="footer">
            <p>Scan QR codes with your smartphone camera or a QR code reader app</p>
        </div>
    </div>

    <script>
        document.addEventListener('DOMContentLoaded', function() {
            const canvas = document.getElementById('qrCode');
            const generateBtn = document.getElementById('BTNGenerate');
            const downloadBtn = document.getElementById('BTNDownload');
            const urlInput = document.getElementById('urlInput');
            const errorMessage = document.getElementById('errorMessage');
            const successMessage = document.getElementById('successMessage');
            
            // Set initial canvas size
            canvas.width = 200;
            canvas.height = 200;
            
            // Draw initial QR code
            generateQRCode();
            
            // Generate QR code when button is clicked
            generateBtn.addEventListener('click', generateQRCode);
            
            // Download QR code when button is clicked
            downloadBtn.addEventListener('click', downloadQRCode);
            
            function generateQRCode() {
                const inputText = urlInput.value.trim();
                
                // Validate input
                if (!inputText) {
                    showError("Please enter some text or URL!");
                    return;
                }
                
                // Validate URL format if it looks like a URL
                if (inputText.includes('.') && !inputText.startsWith('http')) {
                    if (confirm("Would you like to add https:// to make it a valid URL?")) {
                        urlInput.value = 'https://' + inputText;
                        generateQRCode();
                        return;
                    }
                }
                
                // Clear any previous error
                hideError();
                
                // Generate QR code
                QRCode.toCanvas(canvas, inputText, {
                    width: 200,
                    margin: 2,
                    color: {
                        dark: '#000000',
                        light: '#ffffff'
                    }
                }, function (error) {
                    if (error) {
                        showError("Error generating QR code: " + error.message);
                        console.error(error);
                    } else {
                        showSuccess("QR Code generated successfully!");
                        downloadBtn.disabled = false;
                    }
                });
            }
            
            function downloadQRCode() {
                try {
                    const image = canvas.toDataURL("image/png");
                    const link = document.createElement("a");
                    link.download = "qrcode.png";
                    link.href = image;
                    document.body.appendChild(link);
                    link.click();
                    document.body.removeChild(link);
                    
                    showSuccess("QR Code downloaded successfully!");
                } catch (error) {
                    showError("Error downloading QR code: " + error.message);
                    console.error(error);
                }
            }
            
            function showError(message) {
                errorMessage.textContent = message;
                errorMessage.style.display = "block";
                successMessage.style.display = "none";
                downloadBtn.disabled = true;
            }
            
            function showSuccess(message) {
                successMessage.textContent = message;
                successMessage.style.display = "block";
                errorMessage.style.display = "none";
            }
            
            function hideError() {
                errorMessage.style.display = "none";
            }
        });
    </script>
</body>
</html>

Pros:

  • No external requests; QR Code Generation in user Browser
  • Full control over limited appearance (size, colors, margin).
  • You can make it dynamic (e.g., generate a QR code based on user input).

Cons:

  • Requires a basic knowledge of JavaScript.
  • More complex

Method 3: The Classic Way (Generate & Host an Image)

This is the most reliable method. You generate a QR code using a site like QR Code Monkey, qrcode-generator.io, etc. You then download the PNG or SVG file and include it in the website.

Code Example:

<img src="/images/my-blog-qr-code.png" 
     alt="QR Code for My Blog" 
     width="150" 
     height="150" />

Pros:

  • Maximum reliability. No dependencies on external APIs or JavaScript.
  • Fastest loading if optimized correctly.
  • You can design the QR code logos and colors before uploading to the website.

Cons:

  • Requires manual work to generate and upload the image.
  • Not dynamic. To change the data, you need to generate and upload a new image.

Best Practices & Tips

  1. Test QR Code: Always Scan the QR Code On a Different QR Code Scanner App On different phones For Catching errors From the QR Code (Encoding issues, Image blur or too small)
  2. Provide an Alternative Text: The alt text is crucial. It describes the image if Image Fails to Load Correctly or loading image to Show Text Like ("Image Is Loading...")
  3. Explain It "Why Scan": Tell users why to scan qr code. "Scan To Get Official Python Full Tutorial eBook" to visit your website and Buy The eBook
  4. Consider Placement: Don't Hide At the Bottom of the Page. Place Contact US Link Or Social Media Link On the End Of The Post For Sharing.
  5. Keep it Simple: Don't Place a Very Long URL or Text Message; It Becomes a More Complex QR Code Pattern and Sometimes QR Code Scanners Are Unable to Decode QR Code Correctly. Use URL Shortener like cuttly

Which Method Should You Choose?

Method Best For Complexity
Third-Party API Quick prototypes, simple personal projects. Very Low
qrcode.js API Dynamic content, full control, professional sites. Medium
Hosted Image Maximum reliability, high-traffic sites, blogs. Low

For most blogs, Method 3 (Hosted Image) is the recommended choice. It's reliable, fast, and doesn't depend on an external api service and JS Libraries.

Post a Comment

Previous Post Next Post